#include <vcl.h>
#include <stdlib.h>

#include <SysInit.hpp>
#include <jpeg.hpp>
#include <math.hpp>
#include <Ibquery.hpp>

#ifdef _MYSQL
  #pragma link "ZConnect"
  #pragma link "ZMySqlCon"
  #pragma link "ZMySqlQuery"
  #pragma link "ZMySqlTr"
  #pragma link "ZQuery"
  #pragma link "ZTransact"
  #pragma link "ZMySqlQuery"
#endif

#pragma hdrstop
#include <EIC.h>

#include "uFncGDI.h"
#include "uEtat.h"
#include "uDocument.h"
#include "uComposant.h"
#include "uVisualise.h"
#include "Printer.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#define MODULE_TAG MODULE_TAG_DOCUMENT

void __fastcall CopieParams( TParams *Source, TParams *Cible)
{
    Cible->Clear();
    for( int i = 0; i < Source->Count; i++)
    {
        TParam* pCible, *pSource = Source->Items[i];
        pCible = Cible->CreateParam( pSource->DataType, pSource->Name, pSource->ParamType);
        pCible->Value = pSource->Value;
    }
}

//---------------------------------------------------------------------------
//----------------------           DOCUMENT           -----------------------
//---------------------------------------------------------------------------
TDocument* __fastcall NewTDocument(const AnsiString& File, const AnsiString &TitreEtatVoulu) { return new TDocument( File, NULL, NULL, TitreEtatVoulu);}
void       __fastcall DeleteTDocument(TDocument* Doc) { delete  Doc;}
__fastcall TDocument::~TDocument()
{
    m_bEnCoursDestruction = true;
        //Destruction des bandes
    delete m_LstBandes;  m_LstBandes = NULL;

       //Destruction des états
    if( m_ListeEtat)
    {
        for( int i = 0; i < m_ListeEtat->Count; i++)
        {
//            m_nCurEtat = i;
            delete (TEtat*)m_ListeEtat->Items[ i];
            m_ListeEtat->Items[ i] = NULL;
        }
        delete m_ListeEtat; m_ListeEtat = NULL;
    }

    delete m_FontDefaut; m_FontDefaut = NULL;
    delete m_ColorPerso; m_ColorPerso = NULL;
    if( m_FormatCurDefaut)  delete m_FormatCurDefaut;
    if( m_FormatNumDefaut)  delete m_FormatNumDefaut;
    if( m_RGNInvalide)      ::_DeleteObject( TAGL, m_RGNInvalide);
    if( m_hClip)            ::_DeleteObject( TAGL, m_hClip);
    if( m_bListTitreADetruire)  delete m_ListTitre;

    if( m_Styles)
    {
        delete m_Styles; m_Styles = NULL;
    }
}


//---------------------------------------------------------------------------
void __fastcall TDocument::InitVar(const AnsiString &File, TCanvas *CanvasSupport, TStrings *ListTitre)
{
    m_ColorPerso           = new TStringList();
    m_ColorDefaut          = clBlack;
    m_bEnCoursDestruction  = false;

    m_RGNInvalide          =
    m_hClip                = 0;

    m_EtatEnCours          = NULL;
    m_ListeEtat            = new TList();
    m_Titre                = EmptyStr;
    m_Support              = CanvasSupport;
    m_ListTitre            = ListTitre;
    m_File                 = File;
    if( ::FileExists( File))
    {
      try{
      m_File = ::ExpandFileName( File);
      }catch(...)
      {
        try{
        m_File = ::ExpandUNCFileName( File);
        }catch(...){}
      }
/*      if( ExtractFileDir( File).IsEmpty())
      {
        m_File = IncludeTailingBackslash( GetCurrentDir()) + File
      }*/
    }

    m_bListTitreADetruire  = false;
    m_Langue               = 0;
    m_NbLangues            = 1;
    m_NbMiseEnForme        = 0;
    if( m_ListTitre) ListTitre->Clear();
    else
    {
        m_ListTitre = new TStringList();
        m_bListTitreADetruire = true;
    }
    m_Styles = new EICListStyle();
    m_FileVersion = 0;
}
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
__fastcall TDocument::TDocument( const AnsiString &File, TCanvas *CanvasSupport, TStrings *ListTitre, const AnsiString &TitreEtatVoulu):TObject()
{
    InitVar( File, CanvasSupport, ListTitre);

    TFlux *f               = NULL;
    try{
        if( ::FileExists( File))
        {
            int NumeroEtat;
            TYPE_BANDE  eType;
            TBande *b, *bHautDoc = NULL, *bBasDoc = NULL;
            bool bModifMarges = false;
            f = new TFlux( File, fmOpenRead);
            m_FileVersion = f->FileVersion;
            f->Lit( m_Titre);
            m_Marges.Lit( f);
          #ifdef _DEBUG
            if( ((m_Marges.Left.Mm < 6) || (m_Marges.Right.Mm < 6)) &&  IS_MACHINE_INFORMATICIEN() )
            {
              EICAttention( "Les marges gauche ou droite de ce document sont inférieures à 6mm.\r\n"
                            "Il se peut qu'il soit tronqué sur certaines imprimantes.\r\n"
                            "Il faudrait prévoir de passer ces marges à au moins 6mm.");
            }
          #endif
            if( f->FileVersion >= FILE_VERSION( 2, 7))
            {
                m_MargeHorsEntete.Lit( f);
                m_MargeHorsPied.Lit( f);
            }else
            {
                m_MargeHorsEntete = D_NS;
                m_MargeHorsPied = D_NS;
            }

            f->Lit( m_TypePapier);
            m_LargeurDoc.Lit( f);
            m_HauteurDoc.Lit( f);
            f->Lit( m_ColorDefaut);
            f->Lit( &m_FontDefaut);
            f->Lit( &m_FormatNumDefaut);
            f->Lit( &m_FormatCurDefaut);
            f->Lit( m_ColorPerso);
            if( f->FileVersion >= FILE_VERSION( 0, 3))
            {
                m_MargeHorzCp.Lit( f);
                m_MargeVertCp.Lit( f);
                if( f->FileVersion <= FILE_VERSION( 0, 6) && (m_MargeVertCp.Mm >0.5))
                    m_MargeVertCp.Mm = 0.1;

            }
            if( f->FileVersion >= FILE_VERSION( 1, 12))
            {
                f->Lit( m_NbLangues);
                f->Lit( m_NbMiseEnForme);
            }
            if( f->FileVersion >= FILE_VERSION( 1, 13))
            {
                delete m_Styles;
                m_Styles = new EICListStyle(f);
            }
            m_LstBandes   = new TListOfBandes(this, f);
            if( f->FileVersion < FILE_VERSION( 1, 11))
            {
                b = m_LstBandes->SearchBande( e_EnTete);
                if( b){
                    b->LstComposants->DeplaceTout( Marges.Top);
                    b->SetHauteurModifV1_11( b->Hauteur - Marges.Top);
                    bHautDoc = b;
                }
                b = m_LstBandes->SearchBande( e_Pied);
                if( b)
                {
                    b->SetHauteurModifV1_11( b->Hauteur - Marges.Bottom);
                    bBasDoc = b;
                }
            }

            WORD w;
            f->Lit( w); eType = (TYPE_BANDE)w;
            NumeroEtat = -1;
            while( eType == e_Etat)
            {
                TEtat *Etat = NULL;
                DWORD n, Pos;
                NumeroEtat++;
                if( f->FileVersion >= FILE_VERSION( 2, 2))
                    f->Lit( n);
                Pos = f->Position;
//                int nCurEtat = m_ListeEtat->Add( NULL);
                Etat = new TEtat( this, TCoordonnee(), f, TitreEtatVoulu);
                if( !TitreEtatVoulu.IsEmpty() && ( f->FileVersion >= FILE_VERSION( 2, 2)) && (Etat->Titre != TitreEtatVoulu))
                {
                    delete Etat; Etat = NULL;
                    f->Position = Pos + n;
                }else
                {
                    Etat->OriginalFileName         = File;
                    Etat->NumeroInOriginalFileName = NumeroEtat;
                    m_ListeEtat->Add( (void*)Etat);
    //                m_ListeEtat->Items[ nCurEtat] = (void*)Etat;
                    if( m_ListTitre)
                        m_ListTitre->AddObject( Etat->Titre, Etat);
                    if( f->FileVersion < FILE_VERSION( 1, 11))
                    {
                        bool OldbConception = Glob->bConception;
                        Glob->bConception = true;
                        //Conversion de la première bande de chaque état
                        b = Etat->LstBandes->FirstBande();
                        if( b != bHautDoc)
                        {
                            TCoordonnee c = Marges.Top;
                            if( !Etat->DocPdf.IsEmpty()) {c.PixelsY = c.PixelsY + 1; bModifMarges = true;}
                            b->LstComposants->DeplaceTout( c);
                            b->SetHauteurModifV1_11( b->Hauteur - Marges.Top);
                        }
                        b = Etat->LstBandes->LastBande();
                        if( b != bBasDoc)
                        {
                            if( (b->Type == e_Pied) || ((b->Top + b->Hauteur) == Etat->HauteurPage ) )
                                b->SetHauteurModifV1_11( b->Hauteur - Marges.Bottom);
                        }
                        Glob->bConception = OldbConception;
                    }
                }
                if( (f->Position == f->Size) ||
                    (( f->FileVersion >= FILE_VERSION( 2, 2)) && !TitreEtatVoulu.IsEmpty() && Etat) )
                    break;
                f->Lit( w); eType = (TYPE_BANDE)w;
            }
            if( bModifMarges)  m_Marges.Top = m_Marges.Top*2 + 2;

//            m_nCurEtat = 0;
            m_bModified = false;
            delete f;

        }
        else
        {
            m_FontDefaut                = new EICFont();
            m_FontDefaut->PixelsPerInch = Glob->ResolutionX;
            m_HauteurDoc.DixMm       = 2970;
            m_LargeurDoc.DixMm       = 2100;
            m_Marges.Left.DixMm   = 100;
            m_Marges.Top.DixMm    = 100;
            m_Marges.Right.DixMm  = 100;
            m_Marges.Bottom.DixMm = 100;
            m_MargeHorsEntete = D_NS;
            m_MargeHorsPied = D_NS;
            m_MargeHorzCp.Mm = 1;
            m_MargeVertCp.Mm = 0.1;
            m_TypePapier          = DMPAPER_A4;
            m_ColorDefaut         = clBlack;
            m_LstBandes           = new TListOfBandes(this);
            m_FormatNumDefaut     = new EICNumberFmt();
            m_FormatCurDefaut     = new EICCurrencyFmt();
            m_bModified = true;
//            throw EDocException( Exc_Non_Initialise);

/*            TEtat *Etat = new TEtat( this, TCoordonnee());
            m_nCurEtat = m_ListeEtat->Add( (void*)Etat);
            m_ListTitre->Add( Etat->Titre);*/
        }
    }
    catch( EDocException &e)
    {
        if( f) delete f;
        throw;
    }
    if( CurEtat)
        _Invalidate( 0, 0, CurEtat->Largeur.PixelsX, CurEtat->Hauteur.PixelsY);
//    Calculs();
}
void __fastcall TDocument::Assign( const TDocument *Doc)
{
    m_File = Doc->File;
    m_FontDefaut->Assign( Doc->m_FontDefaut);
    m_HauteurDoc = Doc->m_HauteurDoc;
    m_LargeurDoc = Doc->m_LargeurDoc;
    m_Marges = Doc->m_Marges;
    m_MargeHorsEntete = Doc->m_MargeHorsEntete;
    m_MargeHorsPied = Doc->m_MargeHorsPied;
    m_MargeHorzCp = Doc->m_MargeHorzCp;
    m_MargeVertCp = Doc->m_MargeVertCp;
    m_TypePapier = Doc->m_TypePapier;
    m_ColorDefaut = Doc->m_ColorDefaut;
    m_NbLangues = Doc->m_NbLangues;
    m_Langue = Doc->m_Langue;
    TFlux *f = new TFlux();
    Doc->m_LstBandes->Enregistre(f);
    delete m_LstBandes;
    f->Position = 0;
    m_LstBandes = new TListOfBandes( (TObject*)this, f);
    delete f;

    m_Styles->Assign( Doc->Styles);

    m_FormatNumDefaut->Assign( *Doc->m_FormatNumDefaut);
    m_FormatCurDefaut->Assign( *Doc->m_FormatCurDefaut);
}

//---------------------------------------------------------------------------
TBande* __fastcall TDocument::SearchBande( TYPE_BANDE eType)
{
    return m_LstBandes->SearchBande( eType);
}

//---------------------------------------------------------------------------
void __fastcall TDocument::Enregistre()
{
    if( m_File.IsEmpty())
    {
        TSaveDialog *SaveFile = new TSaveDialog(Application->MainForm);
        SaveFile->DefaultExt = "eta";
        SaveFile->Filter     = "Fichers états (*.eta)|*.eta|Tous les fichiers (*.*)|*.*";
        SaveFile->Title = AnsiString( "Enregistrement de ") + Titre;
        if( !SaveFile->Execute()) return;

        if( FileExists( SaveFile->FileName))
        {
            if( Application->MessageBox( (AnsiString("Le fichier ")+ SaveFile->FileName +" existe déjà, voulez-vous l'écraser?").c_str(), "Question...", MB_YESNO) == IDNO)
                return;
            DeleteFile( SaveFile->FileName);
        }
        m_File = SaveFile->FileName;
        delete SaveFile;
    }

    TFlux *f = new TFlux( m_File, /*fmOpenWrite |*/ fmCreate);
    try{try{
        f->Ecrit( m_Titre);
        m_Marges.Enregistre( f);
        m_MargeHorsEntete.Enregistre( f);
        m_MargeHorsPied.Enregistre( f);
        f->Ecrit( m_TypePapier);
        m_LargeurDoc.Enregistre( f);
        m_HauteurDoc.Enregistre( f);
        f->Ecrit( m_ColorDefaut, (TColor)-1);
        f->Ecrit( m_FontDefaut);
        f->Ecrit( m_FormatNumDefaut);
        f->Ecrit( m_FormatCurDefaut);
        f->Ecrit( m_ColorPerso);
        m_MargeHorzCp.Enregistre( f);
        m_MargeVertCp.Enregistre( f);
        f->Ecrit( m_NbLangues);
        f->Ecrit( m_NbMiseEnForme);

        m_Styles->Enregistre( f);

        if( m_LstBandes)
        {
            m_LstBandes->Enregistre( f);
        }

        for( int i = 0; i < m_ListeEtat->Count; i++)
        {
            f->Ecrit( (WORD)e_Etat);
            DWORD Pos2, Pos1 = f->Position;
            f->Ecrit( Pos1);
            ((TEtat*)m_ListeEtat->Items[ i])->Enregistre( f);
            Pos2 = f->Position;
            f->Position = Pos1;
            f->Ecrit( Pos2 - Pos1 - sizeof( Pos1));
            f->Position = Pos2;
        }

        m_bModified = false;
    }catch( EDocException &e){
        throw;
    }
    }__finally{
        delete f;
    }
}
void __fastcall TDocument::SupprimeLangue( byte IdLangue)
{
    if( !m_bEnCoursDestruction && m_ListeEtat)
    {
        TStringList *LstCp = new TStringList();
        for( int i = 0; i < m_ListeEtat->Count; i++)
        {
            ((TEtat*)m_ListeEtat->Items[ i])->GetComposants( ETAT_Cp_Textes_Saisis, LstCp);
        }
        for( int i = 0; i < LstCp->Count; i++)
        {
            ((TCpTexte*)LstCp->Objects[ i])->SupprimeLangue( IdLangue);
        }
        delete LstCp;
        m_NbLangues--;
    }
}
void __fastcall TDocument::AjouteLangue()
{
    if( !m_bEnCoursDestruction && m_ListeEtat)
    {
        TStringList *LstCp = new TStringList();
        for( int i = 0; i < m_ListeEtat->Count; i++)
        {
            ((TEtat*)m_ListeEtat->Items[ i])->GetComposants( ETAT_Cp_Textes_Saisis, LstCp);
        }
        for( int i = 0; i < LstCp->Count; i++)
        {
            ((TCpTexte*)LstCp->Objects[ i])->AjouteLangue( );
        }
        delete LstCp;
        m_NbLangues++;
    }
}

//---------------------------------------------------------------------------
void __fastcall TDocument::ChangeSupport( TObject* Support, bool bForceRefresh)
{
    if( (m_Support != Support) || bForceRefresh)
    {
        m_Support = Support;
        if( CurEtat)
            _Invalidate( 0, 0, CurEtat->Largeur.PixelsX, CurEtat->Hauteur.PixelsY);
    }
}

bool __fastcall TDocument::IsValidSupport( )const
{
    return( IsCanvasSupport());
}

TCanvas* __fastcall TDocument::IsCanvasSupport( )const
{
    if( !::IsBadReadPtr( m_Support, sizeof( TCanvas)) )
        return dynamic_cast<TCanvas*>(m_Support);
    return NULL;
}

//---------------------------------------------------------------------------
void __fastcall TDocument::Draw( TObject* Support, TEtat *Etat)
{
    try{
    TObject* OldSupport = m_Support;
    TEtat* e = Etat? Etat : (m_EtatEnCours?m_EtatEnCours:NULL);

    if( e)
    {
        TEtat *AncEtatEnCours = m_EtatEnCours;
        m_EtatEnCours = Etat;
        ChangeSupport( Support);
        Etat->Draw();
        m_EtatEnCours = AncEtatEnCours;
    }

//    if( f_OnFinDoc) f_OnFinDoc( this);

    m_Support     = OldSupport;
    }catch( EAnnulationImpression &e){}
    catch( ETropDeColonnes &e){}
    catch( EAbort &e){}
    CATCH_EXCEPTION( TAGL);
}

//---------------------------------------------------------------------------
void __fastcall TDocument::Draw( )
{
//    if( f_OnDebutDoc) if( !f_OnDebutDoc( this)) return;

    if( m_EtatEnCours)
        m_EtatEnCours->Draw( );

    if( f_OnFinDoc) f_OnFinDoc( this);
}

//---------------------------------------------------------------------------
void __fastcall TDocument::Calculs( )
{
    if( !m_bEnCoursDestruction && m_ListeEtat)
    {
        for( int i = 0; i < m_ListeEtat->Count; i++)
        {
            ((TEtat*)m_ListeEtat->Items[ i])->Calculs();
        }
    }
}
void __fastcall TDocument::Nettoie( )
{
    if( !m_bEnCoursDestruction && m_ListeEtat)
    {
        for( int i = 0; i < m_ListeEtat->Count; i++)
        {
            ((TEtat*)m_ListeEtat->Items[ i])->Nettoie();
        }
    }
}

//---------------------------------------------------------------------------
/*bool __fastcall TDocument::Selectionne(const TEtat*Etat)
{
    int n = m_ListeEtat->IndexOf( (void*)Etat);
    if( n >= 0)
        SetNumCurEtat( n);
    return (n >= 0);
} */
//---------------------------------------------------------------------------
TEtat* __fastcall TDocument::AjouteEtat( const TCoordonnee &c, const AnsiString& Titre)
{
/*    if( BmpSupport) {BmpSupport->Height = 1; }
    if( BmpSupport) {BmpSupport->Height = Hauteur.PixelsY; }

    m_nCurEtat = m_ListeEtat->Add( (void*)Etat);
    if( Titre.IsEmpty())
        throw EDocException( Exc_Non_Initialise);
    else
        Etat->Titre = Titre;*/

    TEtat *Etat = new TEtat( this, c);
    Etat->Titre = Titre;
    m_ListTitre->Add( Etat->Titre);
    m_ListeEtat->Add( (void*)Etat);
    Modifie();
    Etat->Draw();
    return Etat;
}

TEtat* __fastcall TDocument::AjouteEtat( const TEtat* EtatADupliquer, unsigned long Tag)
{
    if( !EtatADupliquer) return NULL;
    TFlux *f = new TFlux();
    if( EtatADupliquer->Ole) EtatADupliquer->DocOwner->m_NbLangues = m_NbLangues;
    else                     m_NbLangues = min( EtatADupliquer->DocOwner->NbLangues, m_NbLangues);
    EtatADupliquer->Enregistre(f);
    f->Position = 0;
    TEtat *Etat = new TEtat( this, 0, f);
    if( EtatADupliquer->OriginalFileName.IsEmpty())
    {
        Etat->OriginalFileName         = EtatADupliquer->DocOwner->File;
        Etat->NumeroInOriginalFileName = EtatADupliquer->DocOwner->IndexOf( EtatADupliquer);
    }else
    {
        Etat->OriginalFileName         = EtatADupliquer->OriginalFileName;
        Etat->NumeroInOriginalFileName = EtatADupliquer->NumeroInOriginalFileName;
    }
    if( EtatADupliquer->Ole)
        Etat->Ole = new COle( EtatADupliquer->Ole);

    Etat->TakeEvForces            = EtatADupliquer->TakeEvForces;
    Etat->OnDebutEtatForce        = EtatADupliquer->OnDebutEtatForce;
    Etat->OnFinEtatForce          = EtatADupliquer->OnFinEtatForce;
    Etat->OnFirstBandeEtatForce   = EtatADupliquer->OnFirstBandeEtatForce;
    Etat->OnBandeForce            = EtatADupliquer->OnBandeForce;
    Etat->OnAfterFirstBandeInitForce   = EtatADupliquer->OnAfterFirstBandeInitForce;
    Etat->OnChampForce            = EtatADupliquer->OnChampForce;
    Etat->OnTableauForce          = EtatADupliquer->OnTableauForce;
    Etat->OnSQLParamsForce        = EtatADupliquer->OnSQLParamsForce;
    Etat->OnBDInitializedForce    = EtatADupliquer->OnBDInitializedForce;
    Etat->OnErrorForce            = EtatADupliquer->OnErrorForce;
    Etat->OnVariableForce         = EtatADupliquer->OnVariableForce;
    Etat->NbCopies                = EtatADupliquer->NbCopies;
    Etat->EspaceApres             = EtatADupliquer->EspaceApres;
    Etat->ForcerMonetaireSaufZeroSignificatif             = EtatADupliquer->ForcerMonetaireSaufZeroSignificatif;
    if( EtatADupliquer->FormatCurDefaut)
    {
      Etat->FormatCurDefaut         = new EICCurrencyFmt();
      Etat->FormatCurDefaut->Assign(*EtatADupliquer->FormatCurDefaut);
    }
    delete f;
    if( Glob->bConception)
    {
        Etat->Titre += " Ajouté";
        Modifie();
        Etat->Draw();
    }
    m_ListTitre->Add( Etat->Titre);
    m_ListeEtat->Add( (void*)Etat);
    if( (Tag != NO_TAG) && !Etat->Tag) Etat->Tag = Tag;
    return Etat;
}

void __fastcall TDocument::ExchangeEtat( int n, int n1)
{
    m_ListeEtat->Exchange( n, n1);
    m_ListTitre->Exchange( n, n1);
    Modifie();
}

void __fastcall TDocument::DeplaceEtat( int Orig, int Vers)
{
    if( Orig == Vers) return;

    void *v = m_ListeEtat->Items[Orig];
    m_ListeEtat->Delete( Orig);
    m_ListeEtat->Insert( Vers + ((Orig<Vers)?-1:0), v);

    AnsiString s = m_ListTitre->Strings[Orig];
    TObject *o = m_ListTitre->Objects[Orig];
    m_ListTitre->Delete( Orig);
    m_ListTitre->InsertObject( Vers + ((Orig<Vers)?-1:0), s, o);
    Modifie();
}

void __fastcall TDocument::SupprimeEtat( const TEtat* Etat)
{
    if( m_ListeEtat->Count == 1)
    {
        Application->MessageBox( "Cet état est le seul de ce document;\n"                            \
                                      "Vous ne pouvez pas le supprimer.",
                                      "Suppression d'un état...", MB_OK);
        return;
    }
    int n = m_ListeEtat->IndexOf( (void*)Etat);
    m_ListTitre->Delete( n);
    delete Etat;
    m_ListeEtat->Delete( n);
    Modifie();
//    Draw();
}

//---------------------------------------------------------------------------
/*void   __fastcall TDocument::SetCurEtat( const AnsiString &Etat)
{
    int n = m_ListTitre->IndexOf( Etat);
    if( n != -1)
        NumCurEtat = n;
} */
//---------------------------------------------------------------------------
void __fastcall TDocument::InsereBande( TYPE_BANDE eType)
{
    TEtat *AncCurEtat = m_EtatEnCours; m_EtatEnCours = NULL;
    if( m_LstBandes && !m_LstBandes->SearchBande( eType))
        m_LstBandes->Add( eType);
    m_EtatEnCours = AncCurEtat;
}
void __fastcall TDocument::SupprimeBande( TYPE_BANDE eType)
{
    TEtat *AncCurEtat = m_EtatEnCours; m_EtatEnCours = NULL;
    if( m_LstBandes && m_LstBandes->SearchBande( eType))
        m_LstBandes->Delete( eType);
    m_EtatEnCours = AncCurEtat;
}

//---------------------------------------------------------------------------

void __fastcall TDocument::ScrollBasBitmap( const TCoordonnee &YOrigine, const TCoordonnee &YOffset, Graphics::TBitmap* BmpSupport)
{
    TCanvas *c = IsCanvasSupport();
    if( !c || (YOffset.PixelsY == 0)) return;

    TRect rcDest, rcSource;
    rcSource.Left   = 0;
    rcSource.Top    = YOrigine.PixelsY;
    rcSource.Right  = CurEtat->Largeur.PixelsX;
    rcSource.Bottom = CurEtat->Hauteur.PixelsY;

    rcDest = rcSource;
    rcDest.Top      += YOffset.PixelsY;
    rcDest.Bottom   += YOffset.PixelsY;

    if( BmpSupport && (YOffset.PixelsY > 0))  BmpSupport->Height = CurEtat->Hauteur.PixelsY + YOffset.PixelsY;

    c->CopyRect( rcDest, c, rcSource);

    if( BmpSupport && (YOffset.IsNegatif()))   BmpSupport->Height = max( 0, CurEtat->Hauteur.PixelsY + YOffset.PixelsY);

}
//---------------------------------------------------------------------------

/*void   __fastcall TDocument::SetNumCurEtat( int Etat)
{
    m_nCurEtat = min( Etat, m_ListeEtat->Count);
    _Invalidate( 0, 0, CurEtat->Largeur.PixelsX, CurEtat->Hauteur.PixelsY);
};*/
//---------------------------------------------------------------------------

void __fastcall TDocument::_Invalidate()
{
    if( CurEtat)
    {
        _Invalidate( 0, 0, CurEtat->Largeur.PixelsX, CurEtat->Hauteur.PixelsY);
    }
}
void __fastcall TDocument::_Invalidate(int Left,int Top,int Right,int Bottom)
{
    TRect rc;
    rc.Left  = Left;   rc.Top    = Top;
    rc.Right = Right;  rc.Bottom = Bottom;
    _Invalidate( rc);
}
//---------------------------------------------------------------------------

void __fastcall TDocument::_Invalidate(const TRect &rc)
{
    ::_SetRectRgn( TAGL, Glob->hRgnTmp1, rc.Left, rc.Top, rc.Right+1, rc.Bottom+1);
    _Invalidate( Glob->hRgnTmp1);
}
//---------------------------------------------------------------------------
void __fastcall TDocument::_Invalidate( HRGN hRgn)
{
    if( Glob->bConception)
    {
        if( !hRgn)
            ValidateAll();
        else
        {
            if( !m_RGNInvalide)  m_RGNInvalide = ::_CreateRectRgn( TAGL, 0,0,0,0);
            ::_CombineRgn( TAGL, m_RGNInvalide, m_RGNInvalide, hRgn, RGN_OR);
        }
    }
}
//---------------------------------------------------------------------------


void __fastcall TDocument::ValidateAll()
{
    if( Glob->bConception && m_RGNInvalide)
    {
        ::_DeleteObject( TAGL, m_RGNInvalide);
        m_RGNInvalide = 0;
    }
}
//---------------------------------------------------------------------------
HRGN __fastcall TDocument::GetRegionInvalideInRect_ClipIt( const TRect &rc)
{
    RECT r = { rc.Left, rc.Top, rc.Right, rc.Bottom};
    return GetRegionInvalideInRect_ClipIt( r);
}

//---------------------------------------------------------------------------
bool __fastcall TDocument::IsRectInvalideInClip( const RECT  &rc)
{
    if( Glob->bConception)
    {
        RECT r = rc; ::InflateRect( &r, 1,1);//Glob->nRectifPourDessin, Glob->nRectifPourDessin);
        TCanvas *c = IsCanvasSupport();
        if( !rc.right && !rc.left) return false;
        if( c)
        {
            if( IsPrinting()) Glob->EICPrinter->RectifieCoordonnees(r);
            ::_SetRectRgn( TAGL, Glob->hRgnTmp1, 0,0,0,0);
            ::_SetRectRgn( TAGL, Glob->hRgnTmp2, r.left, r.top, r.right, r.bottom);

            if( ::_GetClipRgn( TAGL, c->Handle, Glob->hRgnTmp1) <= 0)
            {
                ::_GetClipBox( TAGL, c->Handle, &r);
                ::_SetRectRgn( TAGL, Glob->hRgnTmp1, r.left, r.top, r.right, r.bottom);
            }
            int nResult = (::_CombineRgn( TAGL, Glob->hRgnTmp2, Glob->hRgnTmp1, Glob->hRgnTmp2, RGN_AND) > NULLREGION)?true:false;
            return nResult;
        }
        return( !c || ::RectVisible( c->Handle, &r) != 0);
    }
    return ((rc.left > 0) && (rc.right > 0)  && (rc.bottom > 0) && (rc.top > 0));
}

//---------------------------------------------------------------------------
HRGN __fastcall TDocument::GetRegionInvalideInRect_ClipIt( const RECT &rc)
{
    if( Glob->bConception && m_RGNInvalide)
    {
        RECT r = rc;
        r.right++; r.bottom++;
TRACEF( TAGL, "GetRegionInvalideInRect_ClipIt [%d,%d,%d,%d]", r.left, r.top, r.right, r.bottom);
        if( !::_RectInRegion( TAGL, m_RGNInvalide, &r)) return 0;
        //if( IsPrinting()) Glob->EICPrinter->RectifieCoordonnees(r);

        if( m_hClip) ::_SetRectRgn( TAGL, m_hClip, r.left, r.top, r.right, r.bottom);
        else         m_hClip = ::_CreateRectRgnIndirect( TAGL, &r);

        switch( ::_CombineRgn( TAGL, m_hClip, m_RGNInvalide, m_hClip, RGN_AND))
        {
            case NULLREGION	   : ::_DeleteObject( TAGL, m_hClip); m_hClip = 0; return 0;
            case SIMPLEREGION  : break;
            case COMPLEXREGION : break;
        }
        TCanvas *c = IsCanvasSupport();
        if( c && c->Handle)
            ::_SelectClipRgn( TAGL, c->Handle, m_hClip);
        return m_hClip;
    }
    return Glob->bConception? 0 : (HRGN)1;
}

//---------------------------------------------------------------------------
void __fastcall TDocument::EffaceRegion( HRGN h)
{
    TCanvas *c = IsCanvasSupport();
    if( !c) return;
    TBrush *b = new TBrush();   b->Style = bsSolid;    b->Color = clWhite;
    ::_FillRgn( TAGL, c->Handle, h, (HBRUSH)b->Handle);
    delete b;
}

//---------------------------------------------------------------------------
/*TCoordonnee __fastcall TDocument::GetHauteur()
{
    TCoordonnee c = ( Portrait? m_Hauteur : m_Largeur);
    return c;
}

//---------------------------------------------------------------------------
TCoordonnee __fastcall TDocument::GetLargeur()
{
    TCoordonnee c = ( Portrait? m_Largeur : m_Hauteur);
    if( m_bConception)
        c += m_LargBarreGauche;
    return c;
}*/

//---------------------------------------------------------------------------
const TCoorRect& __fastcall TDocument::GetMarges( )
{
/*    if( IsPrinting() )//&& Printer_dmPelsWidth && Printer_dmPelsHeight)
    {
        m_crTmp = m_Marges;
        if( Glob->EICPrinter->Canvas)
        {
            m_crTmp.Left.PixelsX -= Glob->EICPrinter->PhysicalOffsetX;
            m_crTmp.Top.PixelsY -= Glob->EICPrinter->PhysicalOffsetY;
            m_crTmp.Right.PixelsX -= Glob->EICPrinter->PhysicalOffsetX;
            m_crTmp.Bottom.PixelsY -= Glob->EICPrinter->PhysicalOffsetY;
        }
        return m_crTmp;
    }
    else*/
    if( HIWORD( TypePapier) && (div( CurEtat->CurrentPage, 2).rem == 0))
    {      
        m_crTmp = m_Marges;
        m_crTmp.Right = m_Marges.Left;
        m_crTmp.Left  = m_Marges.Right;
        return m_crTmp;
    }else
        return m_Marges;
}

TEtat* __fastcall TDocument::GetEtat( const AnsiString& s)const
{
    int i = m_ListTitre->IndexOf( s);
    if( i != -1)
        return (TEtat*)m_ListeEtat->Items[i];
    return NULL;
}
TEtat* __fastcall TDocument::GetEtat( int i)const
{
    ASSERT( (i >= 0) && (i < m_ListeEtat->Count));
    return (TEtat*)m_ListeEtat->Items[i];
}

void __fastcall TDocument::Modifie()
{
    if( Glob->bConception)
    {
        Calculs();
        m_bModified=true;
    }
}
void __fastcall TDocument::FixeNonModifie()
{
    if( !Glob->bConception)
        m_bModified=false;
}

AnsiString __fastcall TDocument::GetTruePathOfFile( const AnsiString &FileName)
{
    if( FileName.IsEmpty()) return FileName;
    AnsiString asFileName = FileName;
    if( !FileExists( asFileName))
    {
       asFileName = IncludeTrailingBackslash(ExtractFilePath(m_File)) + asFileName;
       if( !FileExists( asFileName))
           asFileName = IncludeTrailingBackslash(ExtractFilePath(m_File)) + ExtractFileName(asFileName);
    }
    if( !FileExists( asFileName))
      TRACEF(TAGL, (AnsiString("Le fichier ")+ FileName + " n'existe pas").c_str());
    return asFileName;
}
bool __fastcall TDocument::AImprimer()
{
    bool bReturn = true;
    if( OnDebutDoc)
         if( !OnDebutDoc( this))
            bReturn = false;
    return bReturn;
}
TCoordonnee __fastcall TMyObject::GetLargBarreGauche()const
{
    TCoordonnee c;
    if( Glob->bConception)
        c.PixelsX = Glob->LargBarreGauchePixels;
    return c;
}

//---------------------------------------------------------------------------
//----------------------             ETAT             -----------------------
//---------------------------------------------------------------------------
TEtat*     /*PACKAGE*/ ETATAPI __fastcall NewTEtatOLE(TDocument* Doc, const AnsiString& File, bool Resize, bool bEntetePied)
{
    TEtat* e = NewTEtat(Doc, File);
    if( e->Ole)
    	e->Ole->Resize = Resize;
    if( !bEntetePied)
    {
    	TBande *b;
        e->DebPage = Deb_PageSuiv;
    	e->InsereEnteteEtat();
    	e->InserePiedEtat();
    	b = e->GetBande( e_EnTete, 0); b->Hauteur = 0;
    	b = e->GetBande( e_Pied, 0);   b->Hauteur = 0;
    }
  return e;
}
TEtat* __fastcall NewTEtat(TDocument* Doc, const AnsiString& File){ return new TEtat( Doc, File); }
void   __fastcall DeleteTEtat(TEtat* Etat)                         { delete Etat;}
__fastcall TEtat::~TEtat( )
{
    UnInitialize();
        //Destruction des bandes
    if( m_LstBandes)  delete m_LstBandes; m_LstBandes = NULL;
    if( m_SQLParam)   delete m_SQLParam;
    if( m_LstCpChamp) delete m_LstCpChamp;
    if( m_Ole) delete m_Ole;
    if( m_FormatCurDefaut) delete m_FormatCurDefaut;
}

void __fastcall TEtat::Init( TDocument *DocOwner, TCoordonnee &nTop)
{
    m_LstBandes     = NULL;
    m_Ole           = NULL;
    m_DocOwner      = DocOwner;
    m_bPortrait     = true;
    m_Top           = nTop;
    m_Titre         =
    m_DatabaseName  =
    m_Requete       = EmptyStr;
    m_DebPage       = Deb_AutreDocument;
    m_CurrentPage   =  0;
    m_LstCpColonne  = NULL;
    m_LstCpLigne    = NULL;
    m_LstCpTableau  = NULL;
    m_LstCpEnCours  = NULL;
    m_LstCpExtensibles = NULL;
    m_BandeEnCours  = NULL;
    m_DernBandeDessinee = NULL;
    m_LstCpChamp    = new TList();
    m_Initialized   = false;
    m_EtatAppelant  = NULL;
    m_bFinPage      = false;
    m_bPremBandeEtat= false;
    m_bDebPage      = false;
    m_ForceSautDePage = false;
    m_Saute2Pages     = false;
    m_Tag           = 0;
    m_NumeroInOriginalFileName = -1;
    m_TakeEvForces  = false;
    m_ReinitBDDApresCalculsPage = false;
    m_ResultBdInitialize = false;
    m_CpEndsInPied = DocOwner->CpEndsInPied;
    m_NbBandesSurLaPage     = 0;
    m_EspaceApres           = 0;
    m_ReportFinPageAffiche = false;
    m_ForcerMonetaireSaufZeroSignificatif = false;
}

//---------------------------------------------------------------------------
__fastcall TEtat::TEtat( TDocument *DocOwner, const AnsiString &sOleFile):TMyObject()
{
    try{
        Init( DocOwner, TCoordonnee(0));
        m_DebPage       = Deb_SuitePrec;
        m_LstBandes     = new TListOfBandes( this);
        TBande* b = GetBandeDetail();
        Titre = sOleFile;
      //  b->SautDePageAvant = true;
        TCpTexte* cpTexte = dynamic_cast<TCpTexte*>(b->InsereTexte( TCoordonnee(0), TCoordonnee(0)));
        cpTexte->CaracCp = (Carac_Composant)(cpTexte->CaracCp |car_LargeurEtat | car_HauteurBande);
        cpTexte->Presentation = Tx_Extensible;
        cpTexte->Texte = AnsiString(DebutTexteOLE) + sOleFile;
        cpTexte->PenWidthGauche = 0;
        cpTexte->PenWidthHaut   = 0;
        cpTexte->PenWidthDroit  = 0;
        cpTexte->PenWidthBas    = 0;

        m_Ole = new COle( sOleFile);
        if( !m_Ole->Initialise)
        {
            delete m_Ole;
            m_Ole = NULL;
        }
    }CATCH_EXCEPTION( TAGL);
}
//---------------------------------------------------------------------------

__fastcall TEtat::TEtat( TDocument *DocOwner, TCoordonnee nTop, TFlux *f, const AnsiString &TitreVoulu):TMyObject()
{
try{
    Init( DocOwner, nTop);

    if( !f || !f->Size)
    {
        m_LstBandes     = new TListOfBandes( this);
    }
    else
    {
        f->Lit( m_Titre);
        if( f->FileVersion >= FILE_VERSION( 2, 2))
            if( !TitreVoulu.IsEmpty() && TitreVoulu != m_Titre)
                return;
        f->Lit( *(int*)&m_DebPage);
        f->Lit( m_bPortrait);
        if( f->FileVersion >= FILE_VERSION( 1, 4))
            f->Lit( m_bReportRupture);
        f->Lit( m_DatabaseName);
        f->Lit( m_Requete);
        if( !m_Requete.IsEmpty())
            f->Lit( &m_SQLParam);

        if( f->FileVersion >= FILE_VERSION( 0, 1))
        {
            f->Lit( m_DocPdf);
            if( !m_DocPdf.IsEmpty())
                f->Lit( m_NumPagePdf);
        }
        if( f->FileVersion >= FILE_VERSION( 1, 10))
            f->Lit( m_Tag);

        if( f->FileVersion >= FILE_VERSION( 2, 6))
            f->Lit( m_Filigrane);

        if( f->FileVersion >= FILE_VERSION( 2, 9))
        {
            if( f->FileVersion >= FILE_VERSION( 2, 11))
               f->Lit( *(int*)&m_TypeSQL);
            else{
               bool b;
               f->Lit( b);
               m_TypeSQL = b ? eParadox : eFirebird;
            }


            if( m_TypeSQL != eParadox)
            {
                f->Lit( m_User);
                f->Lit( m_Password);
            }
        }else
          m_TypeSQL = eParadox;
        if( f->FileVersion >= FILE_VERSION( 2, 12))
          f->Lit( m_NomDocGED);
        if( GED_IsClassAuto() )   m_GED_Criteres = CLASSEMENT_AUTO;
        else                      m_GED_Criteres = EmptyStr;
            // BANDES
        m_LstBandes     = new TListOfBandes( this, f);
    }
    m_NiveauBandeBasse = (WORD)-1;
    m_BandeDetail = NULL;
    m_VersPDF = false;
}catch( EAbort &e) {throw;}
catch( EDocException &e){throw;}
CATCH_EXCEPTION( TAGL);

}

//---------------------------------------------------------------------------
void __fastcall TEtat::Enregistre( TFlux *f)const
{
    f->Ecrit( m_Titre);
    f->Ecrit( (int)m_DebPage);
    f->Ecrit( m_bPortrait);
    f->Ecrit( m_bReportRupture);
    f->Ecrit( m_DatabaseName);
    f->Ecrit( m_Requete);
    if( !m_Requete.IsEmpty())
        f->Ecrit( m_SQLParam);

    f->Ecrit( m_DocPdf);
    if( !m_DocPdf.IsEmpty())
        f->Ecrit( m_NumPagePdf);

    f->Ecrit( m_Tag);

    f->Ecrit( m_Filigrane);

    f->Ecrit( m_TypeSQL);
    if( m_TypeSQL != eParadox)
    {
        f->Ecrit( m_User);
        f->Ecrit( m_Password);
    }
    f->Ecrit( m_NomDocGED);
        // BANDES
    m_LstBandes->Enregistre( f);
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
void __fastcall TEtat::InitPrinter( MyCBarre *pBarre)
{
    if( IsPrinting())
    {
/*        m_Mess = new TFrmMessage( "Impression en cours", Screen->ActiveForm, &m_bInterruption);
        if( Screen->ActiveForm)
            SetWindowLong( m_Mess->Handle, GWL_HWNDPARENT, (long)Screen->ActiveForm->Handle);
        SetForegroundWindow( m_Mess->Handle);
        m_Mess->Show();
        m_Mess->Refresh();*/
        DocOwner->Barre = pBarre;
        Glob->EICPrinter->Height = DocOwner->Hauteur;//Hauteur;
        Glob->EICPrinter->Width = DocOwner->Largeur;//Largeur;
    }
}
//---------------------------------------------------------------------------
void __fastcall TEtat::ReleasePrinter( )
{
    TRACEF( TAGL, "ReleasePrinter");
    if( IsPrinting())
    {
        DocOwner->Barre = NULL;
    }
}
//---------------------------------------------------------------------------
void __fastcall TEtat::SetTitre(   const AnsiString& s)
{
    if ( s != m_Titre)
    {
        m_Titre = s;
        Modifie();
        if( DocOwner->ListTitre)
        {
            int n = DocOwner->IndexOf( this);
            if( n != -1)
                DocOwner->ListTitre->Strings[n] = Titre;
        }
    }
}
//---------------------------------------------------------------------------

TCoordonnee __fastcall TEtat::GetHauteur( int bForceHauteurPage)const
{
    try{
    if( Glob->bConception && !bForceHauteurPage)
    {
        TCoordonnee cHauteur = m_LstBandes->Hauteur;
        if( !SearchBande( e_EnTete) )
        {
            TBande* b = DocOwner->LstBandes->SearchBande( e_EnTete);
            if( b ) cHauteur.PixelsY = cHauteur.PixelsY + b->Hauteur.PixelsY;
        }

        if( !SearchBande( e_Pied) )
        {
            TBande* b = DocOwner->LstBandes->SearchBande( e_Pied);
            if( b ) cHauteur.PixelsY = cHauteur.PixelsY + b->Hauteur.PixelsY;
        }
        return cHauteur;
    }
    return m_bPortrait?DocOwner->Hauteur:DocOwner->Largeur;
    }CATCH_EXCEPTION( TAGL)
    return 0;
}
//---------------------------------------------------------------------------
TCoordonnee __fastcall TEtat::GetLargeur( )const
{
    TCoordonnee c = m_bPortrait?DocOwner->Largeur:DocOwner->Hauteur;
    if( Glob->bConception)
        c += LargBarreGauche;
    return c;
}

//---------------------------------------------------------------------------
void __fastcall TEtat::Draw( )
{
    TEtat *AncEtatEnCours = NULL;
    try{try{
        bool bBaseFermee = m_BaseDeDonnee && !m_BaseDeDonnee->Active;
        AncEtatEnCours = DocOwner->EtatEnCours;
		DocOwner->EtatEnCours = this;
        if( !Initialize( )) return;
        if( m_BaseDeDonnee)
            m_BaseDeDonnee->Open();
        TObject* OldSupport;
        if( DocOwner->Barre && !m_EtatAppelant)
        {
            if( m_NumberOfPage)
                DocOwner->Barre->Max2 =  m_NumberOfPage;
            else DocOwner->Barre->Max2 = 1;
        }
        m_BandeEnCours = NULL;
        m_ReportFinPageAffiche = false;
        m_DernBandeDessinee = NULL;
        m_NbPageADessiner = m_NbPageDessinees = 0;
        m_EtatNiveauType_FirstBandeToDraw = 0L;
        if( !Glob->bConception)
        {
            m_bColonneEnCours         = false;
            if( DebPage != Deb_SuitePrec)
            {
                m_CurrentPage             =  0;
                m_BasDerniereBande.Twips  = -1;
            }
            if( m_BaseDeDonnee)
            {
                m_DataSource->OnDataChange = OnDataChange;
                m_BaseDeDonnee->First();
            }
        }
        if( bBaseFermee && DocOwner->f_OnBDInitialized)
            DocOwner->f_OnBDInitialized( this);
TRACEF( TAGL, "m_BasDerniereBande.Twips [%lf]", m_BasDerniereBande.Twips);
        if(Glob->bConception)
             DrawEntetePage();
        if( m_EtatAppelant)
        {
            //BasDerniereBande = m_EtatAppelant->BasDerniereBande;
            if( m_EtatAppelant->DocOwner != DocOwner)
            {
                OldSupport = DocOwner->Support;
                DocOwner->m_Support = m_EtatAppelant->DocOwner->Support;
                DocOwner->_Invalidate( m_EtatAppelant->DocOwner->RGNInvalide);
            }
            switch( m_DebPage)
            {
                case Deb_PagePaire :
                case Deb_PageImpaire :
                case Deb_PageSuiv :
                    ForceSautDePage = true;
                    break;
    #if Deb_Max != 4
        #error "Debut d'etat non reconnu"
    #endif
            }

            //Lancement de l'init du pied
            if( !ForceSautDePage)
            {
                TBande* bPiedEtatAppelant = m_EtatAppelant->SearchBande( e_Pied);
                TBande* bPied = m_LstBandes->SearchBande( e_Pied);
                if( bPiedEtatAppelant && bPied && (bPiedEtatAppelant != bPied))
                {
                    bPied->ReprendHauteur( bPiedEtatAppelant);
                }
            }
        }
        m_bPremBandeEtat = true;
        /*else if( m_EtatAppelant)
        {
            TBande *b = m_EtatAppelant->m_LstBandes->FirstBande();
            if( b->Type == e_EnTete)
                b = m_EtatAppelant->m_LstBandes->NextBande(b);
            TCoordonnee cPlaceEnBas = CalculPlaceVoulueEnBas( b);
            if( m_EtatAppelant->Hauteur - cPlaceEnBas < BasDerniereBande)
            {
                DocOwner->EtatEnCours = AncEtatEnCours;
                m_EtatAppelant->SautDePage( m_EtatAppelant->BandeEnCours, true);
                DocOwner->EtatEnCours = this;
                BasDerniereBande = m_EtatAppelant->BasDerniereBande;
            }
        }*/
      // BANDES
        m_LstBandes->Draw( );

        if(Glob->bConception)
             DrawPiedPage();
        else
        {
            if( m_EtatAppelant &&
                !((m_EtatAppelant->EtatSuivant == this) && ((m_DebPage== Deb_PagePaire)||(m_DebPage== Deb_PageImpaire)))
              )
            {
                TCoordonnee cPlaceEnBas = m_EtatAppelant->CalculPlaceVoulueEnBas( m_EtatAppelant->BandeEnCours, true);
                if( (m_EtatAppelant->Hauteur - cPlaceEnBas) < BasDerniereBande)
                {
                    FinDePage( m_EtatAppelant->BandeEnCours);
                    BasDerniereBande = -1;
                }
            }/*else
                SautDePage( NULL, false);*/
        }
        m_NumberOfPage = m_CurrentPage;
        if( m_EtatAppelant)
        {
            m_EtatAppelant->BasDerniereBande = BasDerniereBande;
            if( m_EtatAppelant->DocOwner != DocOwner)
            {
                m_EtatAppelant->DocOwner->m_Support = DocOwner->m_Support;
                DocOwner->m_Support = OldSupport;
                m_EtatAppelant->DocOwner->_Invalidate( DocOwner->RGNInvalide);
            }
        }else
            ValidateAll( );
        if( DocOwner->Barre && !m_EtatAppelant)
            DocOwner->Barre->Position2 = DocOwner->Barre->Max2;
    }
    catch( EAnnulationImpression &e){ if(m_EtatAppelant || !DocOwner->IsValidSupport()) throw; else if( IsPrinting()) Glob->EICPrinter->Abort();}
    catch( EAbort &e){ if(m_EtatAppelant) throw; }
    CATCH_EXCEPTION( TAG( 10))
    }__finally
    {
        DocOwner->EtatEnCours = AncEtatEnCours;
    }
}


//---------------------------------------------------------------------------
bool __fastcall TEtat::DrawPages( TObject* Support, TBookmark Bookmark,
                                  WORD Etat, WORD Niveau, WORD TypeBande, int PageDebut, int NbPages,
                                  int IndiceRepetPremBande)
{
    TEtat *AncEtatEnCours = DocOwner->EtatEnCours;
    DocOwner->EtatEnCours = this;
    TObject *o = DocOwner->Support;

    try{try{
        if( !Initialize()) return false;
        NbBandesSurLaPage = 0; 
        m_ReportFinPageAffiche = false;
        m_BandeEnCours = NULL;
        m_DernBandeDessinee = NULL;
        DocOwner->ChangeSupport( Support);
        m_NbPageADessiner = NbPages+1; m_NbPageDessinees = 0;
        m_IndiceRepetPremBande = IndiceRepetPremBande;
        if( m_BaseDeDonnee)
        {
            bool bBaseFermee = !m_BaseDeDonnee->Active;
            m_BaseDeDonnee->Open();
            m_DataSource->OnDataChange = NULL;
//            if( Bookmark && m_BaseDeDonnee->BookmarkValid( Bookmark))
//                m_BaseDeDonnee->GotoBookmark( Bookmark);
            if( Bookmark)
            {
                m_BaseDeDonnee->RecNo = (int)Bookmark;
                if( m_BaseDeDonnee->Eof)
                {
                  m_BaseDeDonnee->Prior();
                  if( nbEnreg != 1)
                    m_BaseDeDonnee->Next();
                }
            }
            m_DataSource->OnDataChange = OnDataChange;
            if( m_BaseDeDonnee->Bof)
                OnDataChange(NULL, NULL);
            if( bBaseFermee && DocOwner->f_OnBDInitialized)
                DocOwner->f_OnBDInitialized( this);

        }
/*        for( int i = 0; i < m_LstCpLigne->Count; i++ )
        {
            TCpChamp *Cp = (TCpChamp*)m_LstCpLigne->Items[i];
            Cp->InitValeur( true);
        }*/
        m_CurrentPage                =  PageDebut;
//        m_BasDerniereBande.Twips     = -1;
        m_EtatNiveauType_FirstBandeToDraw = MAKE_ETATNIVEAUBANDE( Etat, Niveau, TypeBande);
        m_bColonneEnCours            = false;

//        DocOwner->SautDePage();

        m_LstBandes->Nettoie();
        if( PageDebut != 1) m_LstBandes->RefreshValRupture( );
        m_LstBandes->Draw( );

//        if( m_BaseDeDonnee && m_BaseDeDonnee->Eof)
//            m_NumberOfPage = m_CurrentPage;

        //SautDePage( NULL, false);
    }
    catch( EAnnulationImpression &e){ if( IsPrinting()) Glob->EICPrinter->Abort(); throw;}
    catch( ETropDeColonnes &e){throw; }
    catch( EAbort &e){}
    CATCH_EXCEPTION( TAG( 15))
    }__finally
    {
        DocOwner->ChangeSupport( o);
        DocOwner->EtatEnCours = AncEtatEnCours;
    }
    return true;
}
void __fastcall TEtat::DrawEtatSuivant(const AnsiString& FileEtatSuivant, const AnsiString &EtatSuivant, bool ForceReinitialize)
{
    TEtat* e= DocOwner->GetEtat( EtatSuivant);
  /*  if( e == this)
    {
        int i = DocOwner->ListTitre->IndexOf( EtatSuivant);
        for( ; i < DocOwner->ListTitre->Count; i++)
        {
            if( DocOwner->ListTitre->Strings[i] == EtatSuivant)
            {
                e = (TEtat*)DocOwner->m_ListeEtat->Items[i];
            }
        }
    }*/
    if( !e)
    {
        if( FileEtatSuivant == DocOwner->File)
            e = DocOwner->GetEtat( EtatSuivant);
        if( !e)
        {
            TDocument *d = new TDocument( FileEtatSuivant);
            e = DocOwner->AjouteEtat( d->GetEtat( EtatSuivant), Tag);
            e->TakeEvForces               = TakeEvForces;
            e->OnDebutEtatForce           = OnDebutEtatForce;
            e->OnFinEtatForce             = OnFinEtatForce;
            e->OnFirstBandeEtatForce      = OnFirstBandeEtatForce;
            e->OnBandeForce               = OnBandeForce;
            e->OnAfterFirstBandeInitForce = OnAfterFirstBandeInitForce;
            e->OnChampForce               = OnChampForce;
            e->OnTableauForce             = OnTableauForce;
            e->OnSQLParamsForce           = OnSQLParamsForce;
            e->OnBDInitializedForce       = OnBDInitializedForce;
            e->OnErrorForce               = OnErrorForce;
            e->OnVariableForce            = OnVariableForce;
            delete d;
        }
    }
    DrawEtatSuivant( e, ForceReinitialize);
}
void __fastcall TEtat::DrawEtatSuivant( TEtat *e, bool ForceReinitialize)
{
    HRGN h = NULL;
    TEtat *eSuivant = NULL;
    try{ try{
    	h = ::_CreateRectRgn( TAGL, 0, 0, 0, 0);
        bool bInitialized;
        if( DocOwner->RGNInvalide)
            ::_CombineRgn( TAGL, h, DocOwner->RGNInvalide, 0/*DocOwner->RGNInvalide*/, RGN_COPY);
        if( IsPrinting() && (DocOwner != e->DocOwner))
            e->DocOwner->Barre = DocOwner->Barre;
        e->Nettoie();
        e->EtatAppelant = this;
        if( ForceReinitialize)
        {
            e->Portrait = Portrait;
            eSuivant = e->EtatSuivant;
            e->EtatSuivant = NULL;
            if( !e->AImprimer( false)) goto finally;
            e->NumeroEnVisu = e->EtatAppelant->NumeroEnVisu;
        }
        bInitialized = e->m_Initialized;
        if( e->Initialize( false))
        {
            bool b;
            if( bInitialized && ForceReinitialize)
            {
                e->InitParamBaseDeDonnee( true);
                b = e->m_ResultBdInitialize;
            }else b = e->m_ResultBdInitialize;
            ForceSautDePage = ForceSautDePage || ( e->Portrait != Portrait);
            if( b)  e->Draw();
        }
        DocOwner->_Invalidate( h);
        finally :
	}CATCH_Annul_TropDeCol_Abort()
    CATCH_EXCEPTION( TAGL)
    }__finally
    {
        if( ForceReinitialize)
        {
            if( DocOwner->OnFinEtat)    DocOwner->OnFinEtat( e);
            e->EtatSuivant = eSuivant;
        }
        ::_DeleteObject( TAGL, h); h = 0;
        if( IsPrinting() && (DocOwner != e->DocOwner))
            e->DocOwner->Barre = NULL;
    }
}
void __fastcall TEtat::Calculs( )
{
    TEtat *AncEtatEnCours = DocOwner->EtatEnCours;
    DocOwner->EtatEnCours = this;
    try{
        LstBandes->Calculs();
    }__finally
    {
        DocOwner->EtatEnCours = AncEtatEnCours;
    }
}

bool __fastcall TEtat::AImprimer( bool bVerifBd)
{
    bool bReturn = true;
//    TEtat *AncEtatEnCours = DocOwner->EtatEnCours;
    if( DocOwner->OnDebutEtat)
        if( !DocOwner->OnDebutEtat( this))
            bReturn = false;
//    DocOwner->EtatEnCours = AncEtatEnCours;
    if( bReturn && bVerifBd)
    {
        InitParamBaseDeDonnee( false);
        bReturn = m_ResultBdInitialize;
    }
    return bReturn;

}

void __fastcall TEtat::InitParamBaseDeDonnee( bool Force)
{
    long lTag = TAGL;
    try{
        if(!m_Requete.IsEmpty())
        {
            TQuery   *QueryParadox  = dynamic_cast<TQuery *>(m_BaseDeDonnee);
            TIBQuery *QueryFirebird = dynamic_cast<TIBQuery *>(m_BaseDeDonnee);
            #ifdef _MYSQL
               TZZMySqlQuery *QueryMySQL = dynamic_cast<TZZMySqlQuery *>(m_BaseDeDonnee);
            if( !m_BaseDeDonnee || Force)
           #else
            if( !m_BaseDeDonnee || !m_nbEnreg || Force)
            #endif
            {
                m_ResultBdInitialize = true;
                if( !m_BaseDeDonnee)
                {
                    int n;
                    switch( m_TypeSQL)
                    {
                      case eParadox :   {
lTag = TAGL;            QueryParadox                  = new TQuery(NULL);
                        QueryParadox->DatabaseName    = m_DatabaseName;
                        m_BaseDeDonnee = QueryParadox;
                        break;
                        }
                      case eFirebird :  {
lTag = TAGL;            TIBDatabase *Database = new TIBDatabase(NULL);
                        QueryFirebird                  = new TIBQuery(NULL);
                        Database->DatabaseName = m_DatabaseName;
                        Database->LoginPrompt = false;
                        Database->SQLDialect = 3;
                        Database->Params->Clear();
                        Database->Params->Add(AnsiString("user_name=")+m_User);
                        Database->Params->Add(AnsiString("password=")+m_Password);
                        Database->Open();

lTag = TAGL;            Database->DefaultTransaction = new TIBTransaction(NULL);
                        Database->DefaultTransaction->Params->Add("read_committed");
                        Database->DefaultTransaction->Params->Add("rec_version");
                        Database->DefaultTransaction->Params->Add("nowait");
                        Database->DefaultTransaction->Active = true;

lTag = TAGL;            QueryFirebird->Database = Database;
                        m_BaseDeDonnee = QueryFirebird;
                        break;
                        }
#ifdef _MYSQL
                      case eMYSQL :   {
lTag = TAGL;
                        TZZMySqlDatabase *Database = new TZZMySqlDatabase(NULL);
                        TZZMySqlTransact *MySQLTransact = new TZZMySqlTransact(NULL);
                        Database->Database = m_DatabaseName.SubString(m_DatabaseName.Pos(":")+1, m_DatabaseName.Length());
                        Database->LoginPrompt = false;
                        Database->Host = m_DatabaseName.SubString(1, m_DatabaseName.Pos(":")-1);
                        Database->Password = m_Password;
                        Database->Login = m_User;

                        Database->Connected = true;
                        MySQLTransact->Database = Database;

                        if (MySqlQuery)
                            QueryMySQL    =  MySqlQuery;
                        else
                            {
                            QueryMySQL    = new TZZMySqlQuery(NULL);
lTag = TAGL;                QueryMySQL->Transaction = MySQLTransact;

lTag = TAGL;                QueryMySQL->Database = Database;
                            }
                            
                        m_BaseDeDonnee = QueryMySQL;
                        break;
                        }
#endif
                    }
                    m_DataSource                    = new TDataSource(NULL);
                    m_DataSource->DataSet           = m_BaseDeDonnee;
lTag = TAGL;    }
                if( m_DataSource && m_BaseDeDonnee)
                {
                    TParams *QueryParams;
                    switch( m_TypeSQL)
                    {
                      case eParadox  : QueryParams = QueryParadox->Params; break;
                      case eFirebird : QueryParams = QueryFirebird->Params; break;
                      #ifdef _MYSQL
                         case eMYSQL : QueryParams = QueryMySQL->Params; break;
                      #endif
                    }
                    m_DataSource->OnDataChange      = NULL;
lTag = TAGL;
                    QueryParams->Clear();

                    switch( m_TypeSQL)
                    {
                    case eParadox  :
                        QueryParadox->ParamCheck      = true;
                        QueryParadox->SQL->Text       = m_Requete;
                        QueryParadox->SessionName     = Glob->SessionName;
                        break;
                    case eFirebird :
                        QueryFirebird->ParamCheck      = true;
                        QueryFirebird->SQL->Text       = m_Requete;
                        break;
                    #ifdef _MYSQL
                    case eMYSQL :
                        QueryMySQL->ParamCheck      = true;
                        QueryMySQL->Sql->Text       = m_Requete;
                        break;
                    #endif
                    }
lTag = TAGL;
                    if( QueryParams && QueryParams->Count)
                    {
                        if( m_SQLParam)
                          QueryParams->AssignValues( m_SQLParam);
                        if( EtatAppelant)
                        {
                            AnsiString s;
                            for( int i=0; i < QueryParams->Count; i++)
                            {
                                TField *f = NULL;
                                if( EtatAppelant->m_BaseDeDonnee)
                                {
                                    try{
                                        f = EtatAppelant->m_BaseDeDonnee->FieldByName(m_SQLParam->Items[i]->Name);
                                    }catch( EDatabaseError &e)
                                    {
                                      f = NULL;
                                    }
                                }
                                if( f)
                                {
                //                            m_BaseDeDonnee->Params->CreateParam( (TFieldType)f->DataType, m_SQLParam->Items[i]->Name, ptInput)->Text = f->Value;
                                    QueryParams->Items[i]->DataType = f->DataType;
                                    QueryParams->Items[i]->Value = f->Value;
                                }else
                                {
                                    TCpChamp* c = dynamic_cast<TCpChamp*>(EtatAppelant->BandeEnCours->GetComposant( m_SQLParam->Items[i]->Name));
                                    if( c)
                                    {
                                        switch( c->Format)
                                        {
                                            case tf_Monetaire :
                                            case tf_Numerique : QueryParams->Items[i]->DataType = ftFloat;    break;
                                            case tf_Booleen	  : QueryParams->Items[i]->DataType = ftBoolean;  break;
                                            case tf_Date	  : QueryParams->Items[i]->DataType = ftDateTime; break;
                                            default           : QueryParams->Items[i]->DataType = ftString;
                                        }
                                        QueryParams->Items[i]->Value = c->Texte;
                                    }
                                }

                            }

                        }


                        if( DocOwner->f_OnSQLParams)
                        {
                            m_ResultBdInitialize = DocOwner->f_OnSQLParams( this, QueryParams);
                        }
                    }
lTag = TAGL;        m_BaseDeDonnee->Open();
lTag = TAGL;        m_nbEnreg = m_BaseDeDonnee->RecordCount;
                    if(m_BaseDeDonnee->RecordCount == 1)
                    {
                        bool bNoRecord = true;
                        for( int i = 0; bNoRecord && i < m_BaseDeDonnee->FieldCount; i++)
                        {
                            if( !m_BaseDeDonnee->Fields->Fields[i]->IsNull)
                                bNoRecord = false;
                        }
                        if( bNoRecord)
                            m_nbEnreg = 0;
lTag = TAGL;        }
                    m_DataSource->OnDataChange      = OnDataChange;
                    if( m_ResultBdInitialize && DocOwner->f_OnBDInitialized)
                        m_ResultBdInitialize = DocOwner->f_OnBDInitialized( this);
                    if( !m_ResultBdInitialize)
                        m_BaseDeDonnee->Close();
lTag = TAGL;    }
            }
        }else m_ResultBdInitialize = true;
        if( m_ResultBdInitialize)
        {
lTag = TAGL;  ReinitChamp();
        }
lTag = TAGL;
    }CATCH_EXCEPTIONc( lTag,
    {
        m_ResultBdInitialize = false;

    })
}
bool __fastcall TEtat::Initialize( bool bShowBarre)
{
    if( Glob->bConception || m_Initialized) return true;
    try{
        bool bCpNbPages         = false;
        m_Initialized = true;
       #ifdef _DEBUG
        if( ( m_DebPage == Deb_AutreDocument) && GED_IsClassAuto() && GED_Criteres == CLASSEMENT_AUTO)
          EICErreur( AnsiString("Le classement automatique n'est pas géré pour l'état : ") + Titre);
       #endif
        m_LstCpEnCours          = new TList();
        m_LstCpColonne          = new TList();
        m_LstCpLigne            = new TList();
        m_LstCpExtensibles      = new TList();
        m_LstCpTableau          = new TStringList();
        m_Formule               = new TCalculDeFormules();
        m_Formule->OnError      = OnErrorEvent;
        m_Formule->OnVariable   = OnVariableEvent;
        m_NumberOfPage          = 0;
        Calculs();
        m_LstBandes->GetComposants( ETAT_Cp_Tableaux_Nommes, m_LstCpTableau);
        m_LstBandes->GetCpCalc( m_LstCpColonne, m_LstCpLigne, m_LstCpExtensibles, bCpNbPages);

        InitParamBaseDeDonnee( false);

        if( !m_ResultBdInitialize)
        {
            if( EtatSuivant)
            {
                BandeEnCours = m_EtatAppelant?m_EtatAppelant->DernBandeDessinee:NULL;
                DrawEtatSuivant( EtatSuivant);
                BandeEnCours = NULL;
            }else
            {
                if( !EtatAppelant || (EtatAppelant->EtatSuivant == this) ) // n'est pas un etat dans un autre
                    NumberOfPage = CurrentPage;
            /*UnInitialize();*/ return false;
            }
        }
        if( !m_EtatAppelant && (m_DebPage == Deb_AutreDocument) && bCpNbPages && !m_NumberOfPage)
        {
            CalculNbPages( bShowBarre);
//            for( int i = 0; i < m_LstCpChamp->Count; i++)
//                ((TCpChamp*)m_LstCpChamp->Items[i])->Initialise = false;
//            delete DocOwner->m_Mess; DocOwner->m_Mess = 0;
        }else if( m_BaseDeDonnee && m_BaseDeDonnee->Active) m_BaseDeDonnee->First();

    }catch( ETropDeColonnes &e){
        UnInitialize();
        throw;
    }
    catch( EAnnulationImpression &e)
    {   throw;
/*        UnInitialize();
        return false;*/
    }
    CATCH_EXCEPTIONc( TAG( 51), {UnInitialize(); return false;} )
    return true;
}
void __fastcall TEtat::UnInitialize( )
{
    if( DocOwner->OnFinEtat)    DocOwner->OnFinEtat( this);
    if( m_Initialized)
    {
        m_Initialized = false;
        try{
            delete m_LstCpColonne;      m_LstCpColonne = NULL;
            delete m_LstCpLigne;        m_LstCpLigne   = NULL;
            delete m_LstCpExtensibles;  m_LstCpExtensibles = NULL;
            delete m_LstCpEnCours;      m_LstCpEnCours = NULL;
            delete m_LstCpTableau;      m_LstCpTableau = NULL;
            delete m_Formule;           m_Formule = NULL;
            Nettoie();
            Calculs();
        }catch(...){}
    }
    if(  m_BaseDeDonnee)
    {
        delete m_DataSource;        m_DataSource = NULL;
        m_BaseDeDonnee->Close();
        switch( m_TypeSQL)
        {
           case eFirebird : {
             TIBQuery *QueryFirebird = dynamic_cast<TIBQuery *>(m_BaseDeDonnee);
             delete QueryFirebird->Database->DefaultTransaction;
             delete QueryFirebird->Database;
             break;
           }
        }
#ifdef _MYSQL
        if (!MySqlQuery)
            {
            delete m_BaseDeDonnee;
            }
        m_BaseDeDonnee = NULL;
#else
        delete m_BaseDeDonnee;      m_BaseDeDonnee = NULL;
#endif
    }
}
void __fastcall TEtat::SetSQLParam( TParams* p)
{
    if( p)
    {
        if( !m_SQLParam) m_SQLParam = new TParams( );

        if( !p->IsEqual( m_SQLParam))
            CopieParams( p, m_SQLParam);//m_SQLParam->Assign( p);
    }
    else if( m_SQLParam)
    {
        delete m_SQLParam;
        m_SQLParam = NULL;
    }
}
void __fastcall TEtat::CalculNbPages( bool bShowBarre)
{
TRACEF( TAGL, "\tCalculNbPages");
    MyCBarre *BarreAvant = dynamic_cast<MyCBarre*>(DocOwner->Barre);
    AnsiString MsgAvant;
    try{
        if( bShowBarre)
        {
            if( !BarreAvant)
            {
                try{
                    DocOwner->Barre = new MyCBarre( "Calcul du nombre de pages", true);
                    DocOwner->Barre->Max = 0;
                }catch(...)
                {
                    DocOwner->Barre = NULL;
                }
            }else{
                MsgAvant = BarreAvant->Messages;
                BarreAvant->Messages = "Calcul du nombre de pages";
            }
        }else{
            if( BarreAvant) DocOwner->Barre = NULL;
        }

        TObject *o = DocOwner->Support;
        DocOwner->ChangeSupport( CanvasCALCUL_NB_PAGES);
        TCoordonnee c = m_BasDerniereBande;
        if( !EtatAppelant)
            m_CurrentPage = 0;
        Draw( );
        if( m_BaseDeDonnee)
        {
            m_BaseDeDonnee->First();
            if( m_ReinitBDDApresCalculsPage)
            {
                m_DataSource->OnDataChange      = NULL;
                m_BaseDeDonnee->Close();
                m_BaseDeDonnee->Open();
                m_DataSource->OnDataChange      = OnDataChange;
                m_ReinitBDDApresCalculsPage = false;
            }
        }
        DocOwner->ChangeSupport( o);
        m_BasDerniereBande = c;
        if( bShowBarre && DocOwner->Barre)
        {
            DocOwner->Barre->Messages = MsgAvant;
            DocOwner->Barre->Refresh();
        }
        ReinitChamp();
//        Nettoie();
    }__finally
    {
        if( !BarreAvant && DocOwner->Barre)
            delete DocOwner->Barre;
        DocOwner->Barre = BarreAvant;
    }
TRACEF( TAGL, "\tCalculNbPages FIN");
}
//---------------------------------------------------------------------------
void __fastcall TEtat::DrawEntetePage( )
{
TRACEF( TAGL, "DrawEntete de page");
    try{
        TBande* b = m_LstBandes->SearchBande( e_EnTete);
        if( b)   b->Draw();
        else  BasDerniereBande = 0;
        if( !CpEndsInPied)
            DrawPiedPage( );
    }CATCH_Annul_TropDeCol_Abort( )
    CATCH_EXCEPTION( TAG( 20))
}

//---------------------------------------------------------------------------
void __fastcall TEtat::DrawPiedPage( )
{
    try{
        TBande* b = m_LstBandes->SearchBande( e_Pied);
        if( b)  b->Draw();
    }CATCH_Annul_TropDeCol_Abort( )
    CATCH_EXCEPTION( TAG( 30))
}
TBande* __fastcall TEtat::GetBandeSpec(TYPE_BANDE eType)const
{
    TBande* b = NULL;
    try{
        b = m_LstBandes->SearchBande( eType);
        if( !b) b = GetBandeDetail()->LstBandesOwner->SearchBande( eType);
    }CATCH_EXCEPTION( TAG( 31))
    return b;
}
//---------------------------------------------------------------------------

TBande* __fastcall TEtat::SearchBande( TYPE_BANDE eType)const
{
    return m_LstBandes->SearchBande( eType);
}
//---------------------------------------------------------------------------

void __fastcall TEtat::InsereBande( TYPE_BANDE eType)
{
    TBande *b = m_LstBandes->SearchBande( eType);
    if( !b || b->OwnerDocument )
        m_LstBandes->Add( eType);
}
void __fastcall TEtat::SupprimeBande( TYPE_BANDE eType)
{
    TBande *b = m_LstBandes->SearchBande( eType);
    if( b && !b->OwnerDocument)
        m_LstBandes->Delete( eType);
}
//---------------------------------------------------------------------------

void __fastcall TEtat::GetComposantsIn( TList* ListeCp, const TCoorRect &rSelection, const TBande* BandeQuiDemande, bool bSelEntier)const
{
    ListeCp->Clear();
    m_LstBandes->GetComposantsIn( ListeCp, rSelection, BandeQuiDemande, bSelEntier);

    RECT  rc, rcDest, rcSel = rSelection.RECTPixels;
    rc.left     = LargBarreGauche.PixelsX;
    rc.right    = rc.left + Largeur.PixelsX;
    if( !SearchBande( e_EnTete) )
    {
        TBande *b = DocOwner->LstBandes->SearchBande( e_EnTete);
        if( b)
        {
            rc.top      = b->Top.PixelsY;
            rc.bottom   = rc.top + b->Hauteur.PixelsY;
            ::IntersectRect( &rcDest, &rc, &rcSel);
            if( !IsRectEmpty( &rcDest))
            {
                TCoorRect cRcDest; cRcDest.RECTPixels = rcDest;
                DocOwner->LstBandes->GetComposantsIn( ListeCp, cRcDest, BandeQuiDemande, bSelEntier);
            }
        }
    }
    if( !SearchBande( e_Pied) )
    {
        TBande *b = DocOwner->LstBandes->SearchBande( e_Pied);
        if( b)
        {
            rc.top      = b->Top.PixelsY;
            rc.bottom   = rc.top + b->Hauteur.PixelsY;
            ::IntersectRect( &rcDest, &rc, &rcSel);
            if( !IsRectEmpty( &rcDest))
            {
                TCoorRect cRcDest; cRcDest.RECTPixels = rcDest;
                DocOwner->LstBandes->GetComposantsIn( ListeCp, cRcDest, BandeQuiDemande, bSelEntier);
            }
        }
    }
}

//---------------------------------------------------------------------------

TComposant* __fastcall TEtat::GetComposant( const TCoordonnee &X, const TCoordonnee &Y, Type_CoinSelectionne &CoinCourant)const
{
    TComposant* Cp=NULL;
    CoinCourant = sel_Aucun;
    if( !SearchBande( e_EnTete) )
    {
        TBande *b = DocOwner->LstBandes->SearchBande( e_EnTete);
        if( b && (Y >= b->Top) && (Y <= b->Top + b->Hauteur))
            Cp = DocOwner->LstBandes->GetComposant( X, Y, CoinCourant);
    }
    if( !Cp && !SearchBande( e_Pied) )
    {
        TBande *b = DocOwner->LstBandes->SearchBande( e_Pied);
        if( b && (Y >= b->Top) && (Y <= b->Top + b->Hauteur))
            Cp = DocOwner->LstBandes->GetComposant( X, Y, CoinCourant);
    }
    if( !Cp)
    {
        Cp = LstBandes->GetComposant( X, Y, CoinCourant);
    }
    return Cp;
}
//---------------------------------------------------------------------------

TComposant* __fastcall TEtat::GetComposant(const AnsiString &s)const
{
    TComposant* Cp=NULL;
    if( DocOwner->LstBandes)
    {
        if( !SearchBande( e_EnTete) )
        {
            TBande *b = DocOwner->LstBandes->SearchBande( e_EnTete);
            if( b) Cp = b->GetComposant( s);
        }
        if( !Cp && !SearchBande( e_Pied) )
        {
            TBande *b = DocOwner->LstBandes->SearchBande( e_Pied);
            if( b) Cp = b->GetComposant( s);
        }
    }
    if( !Cp)
    {
        Cp = LstBandes->GetComposant( s);
    }
    return Cp;
}
//---------------------------------------------------------------------------

void __fastcall TEtat::GetComposants( enum TypesComposants TypeCp, TStrings *LstCp)const
{
    if( DocOwner->LstBandes)
    {
        if( !SearchBande( e_EnTete) )
        {
            TBande *b = DocOwner->LstBandes->SearchBande( e_EnTete);
            if( b) b->GetComposants( TypeCp, LstCp);
        }
        if( !SearchBande( e_Pied) )
        {
            TBande *b = DocOwner->LstBandes->SearchBande( e_Pied);
            if( b) b->GetComposants( TypeCp, LstCp);
        }
    }
    LstBandes->GetComposants( TypeCp, LstCp);
}
//---------------------------------------------------------------------------
void __fastcall TEtat::InvalideComposantsAttacheA( const AnsiString &ChpAttache)
{
    if( LstBandes) LstBandes->InvalideComposantsAttacheA( ChpAttache);
}
//---------------------------------------------------------------------------
void __fastcall TEtat::NettoieComposantsAttacheA( const AnsiString &ChpAttache)
{
    if( LstBandes) LstBandes->NettoieComposantsAttacheA( ChpAttache);
}
//---------------------------------------------------------------------------

TBande* __fastcall TEtat::GetBande( const TCoordonnee &cY)const
{
    TBande* b = m_LstBandes->GetBande( cY);

    if( !b)
    {
        if( !SearchBande( e_EnTete) )
        {
            b = DocOwner->LstBandes->SearchBande( e_EnTete);
            if( b && b->IsInBande( cY) ) return b;
        }

        if( !SearchBande( e_Pied) )
        {
            b = DocOwner->LstBandes->SearchBande( e_Pied);
            if( b && b->IsInBande( cY) ) return b;
        }
    }
    return b;
}
//---------------------------------------------------------------------------
bool __fastcall TEtat::QuEstCeQuiYaDessous( const TCoordonnee &X, const TCoordonnee &Y, TBande **BandeCourante, TComposant **CpCourant, Type_CoinSelectionne *CoinCourant, bool *bOnEstDansLaMarge)const
{
    TBande              *vBandeCourante     = GetBande( Y);
    TComposant          *vCpCourant         = NULL;
    Type_CoinSelectionne vCoinCourant       = sel_Aucun;
    bool                 vbOnEstDansLaMarge = false,
                         bResult = true;
    if( (X >= TCoordonnee(0)) && (X <= Largeur ) &&
        (Y >= TCoordonnee(0)) && (Y <= Hauteur ) && vBandeCourante)
    { // On est dans de l'état
        vbOnEstDansLaMarge = ( (X < LargBarreGauche + DocOwner->Marges.Left) ||
                               (X > Largeur - DocOwner->Marges.Right ) /*||
                               (Y < DocOwner->Marges.Top)  ||
                               (Y > Hauteur - DocOwner->Marges.Bottom)*/ );
        vCpCourant = vBandeCourante->LstComposants->GetComposant( X, Y, vCoinCourant);
    }
    else bResult = false;
    if( BandeCourante)      *BandeCourante       = vBandeCourante;
    if( CpCourant)          *CpCourant           = vCpCourant;
    if( CoinCourant)        *CoinCourant         = vCoinCourant;
    if( bOnEstDansLaMarge)  *bOnEstDansLaMarge   = vbOnEstDansLaMarge;
    return bResult;
}
//---------------------------------------------------------------------------
WORD __fastcall TEtat::GetNiveauBandeBasse( )const
{
    if( m_NiveauBandeBasse == (WORD)-1)
    {
        WORD w;
        TListOfBandes *LstBd;
        for( LstBd = m_LstBandes, w = 0;
                LstBd ;
             LstBd = LstBd->SearchBande( e_Principal)->LstBandes, w++);
        *(const_cast<WORD*>( &m_NiveauBandeBasse)) = (WORD)(w-1);
    }
    return m_NiveauBandeBasse;
}
//---------------------------------------------------------------------------

TBande*  __fastcall TEtat::GetBande( TYPE_BANDE eType, WORD wNiveau)const
{
    TBande        *b;
    if( !wNiveau)
        return m_LstBandes->SearchBande( eType);
    for( b = m_LstBandes->SearchBande( e_Principal);
            b && b->LstBandes && (b->Niveau != wNiveau);
         b = b->LstBandes->SearchBande( e_Principal)    );
    if( b && b->Niveau == wNiveau)
    {
        return b->LstBandesOwner->SearchBande( eType);
    }

    /*    for( LstBd = m_LstBandes;
            b && LstBd;
         LstBd = b->LstBandes)
    {
        b = LstBd->SearchBande( e_Principal);
        if( b && b->Niveau == wNiveau)
            break;
    }

    if( LstBd)
        b = LstBd->SearchBande( wType);*/

/*    if( !wNiveau && !b  && ( (wType == e_EnTete) || (wType == e_Pied)) )
        b = DocOwner->LstBandes->SearchBande( wType);*/
    return NULL;
}
//---------------------------------------------------------------------------

TCoordonnee  __fastcall TEtat::GetHauteurEntete()const
{
    if( !Glob->bConception)
    {
        TCoordonnee c;
        TBande* b = LstBandes->SearchBande( e_EnTete);
        if( b) c = b->Hauteur;
//        else{
            c += DocOwner->Marges.Top;
//        }
        if( DocOwner->MargeHorsEntete != D_NS)
            c = max( c, DocOwner->MargeHorsEntete);
        return c;
    }
    return 0;
}
//---------------------------------------------------------------------------

TCoordonnee  __fastcall TEtat::GetHauteurPied()const
{
    if( !Glob->bConception)
    {
        TCoordonnee c;
        TBande* b = LstBandes->SearchBande( e_Pied);
        if( b) c = b->Hauteur;
        c += DocOwner->Marges.Bottom;

        if( DocOwner->MargeHorsPied != D_NS)
            c = max( c, DocOwner->MargeHorsPied);
        return c;
    }
    return 0;
}

//---------------------------------------------------------------------------
TCoordonnee __fastcall TEtat::GetTop( )const
{
    if ( !m_CurrentPage)  return m_Top;
    else                  return GetHauteurEntete();
}
//---------------------------------------------------------------------------
void __fastcall TEtat::ReinitChamp()
{
    if( m_LstCpColonne)
        for( int i = 0; i < m_LstCpColonne->Count; i++)
        {
            ((TCpChamp*)m_LstCpColonne->Items[i])->TCpTexte::Texte = "0";
            ((TCpChamp*)m_LstCpColonne->Items[i])->Initialise = false;
        }

    if( m_LstCpExtensibles)
        for( int j = 0; j < m_LstCpExtensibles->Count; j++)
            ((TCpTexte*)m_LstCpExtensibles->Items[j])->nLastCharPrint = -1;
}
void __fastcall TEtat::Nettoie( )
{
    m_NbPageADessiner               = m_NbPageDessinees = 0;
    m_EtatNiveauType_FirstBandeToDraw    = 0;
    m_BandeEnCours                  = NULL;
    m_DernBandeDessinee             = NULL;
    m_CpChampEnCours                = NULL;
    m_CurrentPage                   =  0;
    m_BasDerniereBande.Twips        = -1;
    m_bColonneEnCours               = false;
    m_NiveauBandeBasse = (WORD)-1;
    m_BandeDetail = NULL;
    m_EtatAppelant = NULL;
    ReinitChamp();

    m_LstBandes->Nettoie();
}
//---------------------------------------------------------------------------
void __fastcall TEtat::FinDePage( TBande* FirstOnNewPage)
{
  try{
    m_bFinPage = true;
    TBande *b;
    if( (BasDerniereBande.Twips >= 0) || Glob->bConception)
    {
        if( m_BandeEnCours)
        {
        //            if( ((FirstOnNewPage->EtatOwner == this) && bColonneEnCours)  ||
 //               (!GetBandeDebColonne() && (FirstOnNewPage && (FirstOnNewPage->operator <( MAKE_ETATNIVEAUBANDE( Niveau, 1, e_Fin))) )))
            if( FirstOnNewPage &&
                ( ( bColonneEnCours && (FirstOnNewPage->EtatOwner == this) &&
                    ( (m_DernBandeDessinee->Type == e_Principal) || (m_DernBandeDessinee->Type >= e_Utilisateur) ) &&
                    (GetBandeDetail()->Niveau == m_DernBandeDessinee->Niveau) )  ||
                  (!GetBandeDebColonne() && (FirstOnNewPage && (FirstOnNewPage->operator <( MAKE_ETATNIVEAUBANDE( Niveau, 1, e_Fin))) ))))
            {
                b = GetBandeReportFinPage();
                if( b) b->Draw();
                m_ReportFinPageAffiche = true;
            }
            if( bColonneEnCours)
            {
                b = GetBandeFinColonne();
                if( b) b->Draw();
            }
            if( FirstOnNewPage && (FirstOnNewPage->EtatOwner == this))
            {
                b = GetBandeSpec( e_SautDePage);
                if( b) b->Draw();
            }/*else if( DocOwner->f_OnDrawEtatEnDessous)
            {
                if( DocOwner->f_OnDrawEtatEnDessous( this))
                {
                    return;
                }
            }*/
        }
        if( CpEndsInPied)
            DrawPiedPage();
#define DECALAGE 200
        if( !m_Filigrane.IsEmpty())
        {
            TCoordonnee l = Largeur, h = Hauteur;
            if( Glob->bVersionDeDemonstration)
            {
//                int Angle = atan( Hauteur.PixelsX / Largeur.PixelsX);
                l = Largeur - TCoordonnee::DixMm2Twips( DECALAGE);
                h = ::MulDiv( l.Twips, Hauteur.Twips, Largeur.Twips);
            }
            DessineFiligrane( DocOwner->Support, l, h,
                              DocOwner->Marges, m_Filigrane);
        }
        if( Glob->bVersionDeDemonstration)
        {
            TCoorRect       RectFiligrane = DocOwner->Marges;
            if( !m_Filigrane.IsEmpty())
            {
                RectFiligrane.Left += TCoordonnee::DixMm2Twips( DECALAGE);
                RectFiligrane.Top  += ::MulDiv( TCoordonnee::DixMm2Twips( DECALAGE), Hauteur.Twips, Largeur.Twips);
            }
            DessineFiligrane( DocOwner->Support, Largeur, Hauteur,
                              RectFiligrane, "Version de démonstration");
        }
        if( m_LstCpColonne)
        {
            for( int i = 0; i < m_LstCpColonne->Count; i++)
            {
                TCpChamp* cpC = ((TCpChamp*)m_LstCpColonne->Items[i]);
                if( (cpC->Type == tc_Calcule) && (cpC->TypeCalcul == tcalc_Colonne) && (cpC->TypeCalculCol == tCalcCol_Total_Page))
                {
                    cpC->TCpTexte::Texte = "0";
                    cpC->Initialise = false;
                }
            }
        }

        if( DocOwner->f_OnFinPage)
            DocOwner->f_OnFinPage( this);
    }
    m_bFinPage = false;
  }
  CATCH_Annul_TropDeCol_Abort( )
  CATCH_EXCEPTION( TAGL)
}
void __fastcall TEtat::NouvellePage( TBande* FirstOnNewPage, bool bDebutEffacable)
{
  try{ try{
    TEtat *EtatPage = this;
    if( m_EtatAppelant) EtatPage = m_EtatAppelant;
    for( int cpt = 0; cpt < (Saute2Pages?2:1); cpt++)
    {
        if( cpt == 1)
        {
            if( DocOwner->f_OnFinPage)
                DocOwner->f_OnFinPage( this);
        }
        EtatPage->CurrentPage = EtatPage->CurrentPage+1;

        if( DocOwner->Barre)
        {
            if( !EtatPage->NumberOfPage)
            {
                if( DocOwner->m_Barre->DoubleAffichage)
                {
                    DocOwner->Barre->Max2 ++;
                    DocOwner->Barre->MessageInfo2 = AnsiString("Page ") + EtatPage->CurrentPage;
                }else
                {
                    DocOwner->Barre->MessageInfo = AnsiString("Page ") + EtatPage->CurrentPage;
                }
            }else
            {
                if( DocOwner->Barre->DoubleAffichage)
                    DocOwner->Barre->MessageInfo2 = AnsiString("Page ") + EtatPage->CurrentPage + "/" + EtatPage->NumberOfPage;
                else
                    DocOwner->Barre->MessageInfo = AnsiString("Page ") + EtatPage->CurrentPage + "/" + EtatPage->NumberOfPage;
            }
            if( DocOwner->Barre->DoubleAffichage)
                DocOwner->Barre->Position2 = EtatPage->CurrentPage-1;
        }
        if( cpt == 1)
        {
            if( DocOwner->f_OnDebutPage)
                DocOwner->f_OnDebutPage( FirstOnNewPage);
        }else{
            if( m_EtatAppelant) m_EtatAppelant->InitialiseNouvellePage( FirstOnNewPage, true);
            InitialiseNouvellePage( FirstOnNewPage, m_EtatAppelant == NULL);
        }

        if( EtatPage->NbPageADessiner)
        {
            int nNbPageADessiner = EtatPage->NumberOfPage? min( EtatPage->NumberOfPage+1, EtatPage->NbPageADessiner):EtatPage->NbPageADessiner;
            if( DocOwner->IsValidSupport() || (DocOwner->m_Support == CanvasIMPRIME_STOP) )
                EtatPage->NbPageDessinees++;
            if( nNbPageADessiner - EtatPage->NbPageDessinees == 0)
                throw EAbort( "Interruption");
            if( DocOwner->m_Support == CanvasIMPRIME_DS_VIDE_EMF)
            {
                if( nNbPageADessiner - (EtatPage->NbPageDessinees+1) == 0)
                    throw EAbort( "Interruption");
            }
        }

        if( IsPrinting() && (DocOwner->m_Support != CanvasCALCUL_NB_PAGES) && (DocOwner->m_Support != CanvasIMPRIME_DS_VIDE) )
        {
            int Cas = 0;
            if( Glob->EICPrinter->Printing &&
                ( ((Glob->EICPrinter->Orientation == poLandscape) && m_bPortrait && !Glob->EICPrinter->PaysagePortraitAssembles) ||
                  ((Glob->EICPrinter->Orientation == poPortrait) && !m_bPortrait && !Glob->EICPrinter->PaysagePortraitAssembles) ||
                  (Glob->EICPrinter->CopieSupport() && (Glob->EICPrinter->Copies != NbCopies))  ))
            {
                Cas = 1;
                if( !Glob->EICPrinter->PDF)
                    Glob->EICPrinter->EndDoc();
                Glob->EICPrinter->Orientation = m_bPortrait? poPortrait : poLandscape;
                Glob->EICPrinter->Title = NomDocGED;
                Glob->EICPrinter->Copies = NbCopies;
                if( !Glob->EICPrinter->PDF)
                    Glob->EICPrinter->BeginDoc(bDebutEffacable);
                else
                    Glob->EICPrinter->NewPage(bDebutEffacable);
                DocOwner->ChangeSupport( Glob->EICPrinter->Canvas, true);
            }
            else
            {
                if( !Glob->EICPrinter->Printing)
                {  //première feuille
                Cas = 2;
                    Glob->EICPrinter->Orientation = m_bPortrait? poPortrait : poLandscape;
                    Glob->EICPrinter->Title = NomDocGED;
                    Glob->EICPrinter->Copies = NbCopies;
                    Glob->EICPrinter->BeginDoc(bDebutEffacable);
                    DocOwner->ChangeSupport( Glob->EICPrinter->Canvas, true);
                }
                else
                {
                Cas = 3;
                    if( Glob->EICPrinter->PaysagePortraitAssembles)
                      Glob->EICPrinter->Orientation = m_bPortrait? poPortrait : poLandscape;
                    Glob->EICPrinter->NewPage(bDebutEffacable);
                    DocOwner->m_Support = Glob->EICPrinter->Canvas;
                }
            }
            #ifdef _DEBUG
            if( !Glob->EICPrinter->PDF && (Printer()->Orientation != (m_bPortrait? poPortrait : poLandscape)))
            {
              throw EUser( TAGL, AnsiString( "Erreur document portrait en paysage ou inverse\n")+
                                  "Cas " + Cas + "\n"
                                  "Glob->EICPrinter->Printing" + (int)Glob->EICPrinter->Printing + "\n");
            }
            #endif

        }
    }
  }
  CATCH_Annul_TropDeCol_Abort( )
  CATCH_EXCEPTION( TAGL)
  }__finally
  {
    Saute2Pages = false;
  }
}
void __fastcall TEtat::InitialiseNouvellePage( TBande* FirstOnNewPage, bool bDrawEntete)
{
  try{
    for( int i = 0; i < m_LstCpChamp->Count; i++)
    {
        TCpChamp *CpChamp = (TCpChamp*)m_LstCpChamp->Items[i];
        if( (CpChamp->BandeHt != FirstOnNewPage) &&
            (m_LstCpColonne->IndexOf( CpChamp) == -1) )
            CpChamp->Initialise = false;
    }

    if( bDrawEntete)
    {
        TDataChangeEvent DataChange;
        if( m_DataSource)
        {
            DataChange = m_DataSource->OnDataChange;
            m_DataSource->OnDataChange = NULL;
        }
        if( DocOwner->f_OnDebutPage)
            DocOwner->f_OnDebutPage( FirstOnNewPage);
        if( m_DataSource) m_DataSource->OnDataChange = DataChange;
    }
  }
  CATCH_Annul_TropDeCol_Abort( )
  CATCH_EXCEPTION( TAGL)
}
void __fastcall TEtat::DebutDePage( TBande* FirstOnNewPage, bool bDrawEntete, TBande* LastBdDessinee)
{
  try{
    TBande *b;
m_bDebPage = true;
    if( bDrawEntete)
        DrawEntetePage();
    TBande *bDebColonne = GetBandeDebColonne();
    bool bSectionApresDebColonne = bDebColonne && (bDebColonne->LstBandesOwner == m_LstBandes);
    if( ReportRupture && !bSectionApresDebColonne)
        DebutDeSections( FirstOnNewPage);
    if( bColonneEnCours)//FirstOnNewPage && (FirstOnNewPage->Type == e_Principal))
    {
        if( bDebColonne) bDebColonne->Draw();
        if( ReportRupture && bSectionApresDebColonne)
            DebutDeSections( FirstOnNewPage);
    }
    if( m_ReportFinPageAffiche)
    /*(bColonneEnCours &&
         ( (LastBdDessinee->Type == e_Principal) || (LastBdDessinee->Type >= e_Utilisateur) ) ) ||
        (!bDebColonne && FirstOnNewPage && FirstOnNewPage->operator >( MAKE_ETATNIVEAUBANDE( Niveau, 1, e_Debut))))*/
    {
        b = GetBandeReportDebPage();
        if( b) b->Draw();
    }
    m_ReportFinPageAffiche = false;
m_bDebPage = false;
  }
  CATCH_Annul_TropDeCol_Abort( )
  CATCH_EXCEPTION( TAGL)
  m_bDebPage = false;
}

void __fastcall TEtat::SautDePage( TBande* FirstOnNewPage, bool bDebutEffacable, bool bContinue)
{
    TBande *b, *LastBdDessinee = m_DernBandeDessinee;
    try{

        if( (NbBandesSurLaPage == 0) && (BasDerniereBande.Twips >= 0) ) return;

        bool bInternAutreEtat = m_EtatAppelant && (m_EtatAppelant->EtatSuivant != this);
     // BAS DE PAGE
        if( m_bPremBandeEtat && m_EtatAppelant) m_EtatAppelant->FinDePage( FirstOnNewPage);

        else                                    FinDePage( FirstOnNewPage);

        if( m_bPremBandeEtat)
        {
            switch( m_DebPage)
            {
                case Deb_PagePaire :   Saute2Pages = (div( CurrentPage, 2).rem == 0); break;
                case Deb_PageImpaire : Saute2Pages = (div( CurrentPage, 2).rem == 1); break;
    #if Deb_Max != 4
        #error "Debut d'etat non reconnu"
    #endif
            }
        }

        NbBandesSurLaPage=0;
        if( bContinue )
        {
     // INIT NOUVELLE PAGE
            if( BasDerniereBande.Twips != -2)
            {
                if( bInternAutreEtat) m_EtatAppelant->NouvellePage( FirstOnNewPage, bDebutEffacable);
                else                  NouvellePage( FirstOnNewPage, bDebutEffacable);
            }else
            {
            //  InitialiseNouvellePage( FirstOnNewPage, m_EtatAppelant == NULL);
              if( DocOwner->f_OnDebutPage)
                DocOwner->f_OnDebutPage( FirstOnNewPage);
            }
            Saute2Pages = false;
     // HAUT DE PAGE
            if( bInternAutreEtat) m_EtatAppelant->DebutDePage( FirstOnNewPage, true, LastBdDessinee);
            DebutDePage( FirstOnNewPage, !bInternAutreEtat, LastBdDessinee);
        }
        NbBandesSurLaPage=0;

    }CATCH_Annul_TropDeCol_Abort()
    catch( Exception &e)
    {   throw EUser( TAG( 40), e);}
}

//---------------------------------------------------------------------------
void __fastcall TEtat::ValideDebutDePage( bool bValide)
{
    if( IsCanvasSupport() && IsPrinting() )
    {
        Glob->EICPrinter->ValideDebutPage( bValide);
        DocOwner->ChangeSupport( Glob->EICPrinter->Canvas);
    }
}

//---------------------------------------------------------------------------
void __fastcall TEtat::OnDataChange(TObject* Sender, TField* Field)
{
    if( !(   DocOwner->IsValidSupport( )
          || (DocOwner->Support == CanvasCALCUL_NB_PAGES)
          || ( (DocOwner->Support == CanvasIMPRIME_DS_VIDE) && !NumberOfPage))) return;
    TStringList *LstChampAReinitialiser = new TStringList();
    try{try{
        TBande *bADessiner;

        if( m_BaseDeDonnee)
        {
            TBande *b;
            bool bRuptAv = false;
            AnsiString    ChpRupture;
            m_DataSource->OnDataChange = NULL;
            m_DataSource->DataSet = NULL;

        // INIT DES TOTAUX PAR COLONNE
        //    if( m_BaseDeDonnee->Bof)

            for( b = m_LstBandes->SearchBande( e_Principal);
                    b;
                 b = b->LstBandes? b->LstBandes->SearchBande( e_Principal) : NULL)
            {
                if( !b->ChpRupture.IsEmpty() && (b->LstBandes->bRuptureVisible || (bRuptAv && b->FieldRupture)) )
                {
                    if( bRuptAv || (b->ValeurChpRupture != b->FieldRupture->AsString ))
                        bRuptAv = true;

                    if( bRuptAv)
                        LstChampAReinitialiser->Add( b->ChpRupture);
                }
            }
            // Si on est en début de fichier on initialise les var qui ne se trouve pas sur une rupture
            if( m_BaseDeDonnee->Bof)
                LstChampAReinitialiser->Add( EmptyStr);

            if( LstChampAReinitialiser->Count)
            {
          // FINS DE SECTIONS
                if( !m_BaseDeDonnee->Eof)
                    m_BaseDeDonnee->Prior();
                if( !m_BaseDeDonnee->Bof)
                {   // pas en Début de page
                    bADessiner = GetBandeDetail()->LstBandesOwner->SearchBande( e_FinColonne);
                    if( bADessiner || GetBandeDetail()->LstBandesOwner->SearchBande( e_DebutColonne))
                        bColonneEnCours = false;
                    if( bADessiner)  bADessiner->Draw();
                    for( b = GetBandeDetail()->LstBandesOwner->BandeOwner;
                            b;
                         b = b->LstBandesOwner->BandeOwner)
                    {
                        if( (LstChampAReinitialiser->IndexOf( b->ChpRupture) !=-1) &&
                            (b->LstBandes && b->LstBandes->bRuptureVisible))
                        {
                            bADessiner = b->LstBandes? b->LstBandes->SearchBande( e_Fin) : NULL;
                            if( bADessiner)  bADessiner->Draw();
                        }
                    }
                    m_BaseDeDonnee->Next();
                }
          // RAZ CHAMPS CALCULES PAR COLONNE
                TCpChamp *Cp;
                for( int i = 0; i < m_LstCpColonne->Count; i++)
                {
                    AnsiString s;
                    Cp = (TCpChamp*)m_LstCpColonne->Items[i];
                    s = (Cp->RuptureAssociee=="Général")?EmptyStr:Cp->RuptureAssociee;
                    if( LstChampAReinitialiser->IndexOf( s) != -1)
                        Cp->Texte = "0";
                }
            }
        }

        for( int i = 0; i < m_LstCpChamp->Count; i++)
            ((TCpChamp*)m_LstCpChamp->Items[i])->Initialise = false;

        if( m_BaseDeDonnee && !m_BaseDeDonnee->Bof && !m_BaseDeDonnee->Eof && LstChampAReinitialiser->Count)
        {
            DebutDeSections( LstChampAReinitialiser);

            bADessiner = GetBandeDetail()->LstBandesOwner->SearchBande( e_DebutColonne);
            if( bADessiner) bADessiner->Draw();
            if( bADessiner || GetBandeDetail()->LstBandesOwner->SearchBande( e_FinColonne))
                bColonneEnCours = true;
        }

    }CATCH_Annul_TropDeCol_Abort()
    catch( Exception &e){}
    }__finally
    {
        if( m_BaseDeDonnee)
        {
            m_DataSource->DataSet = m_BaseDeDonnee;
            m_DataSource->OnDataChange = OnDataChange;
        }
        delete LstChampAReinitialiser;
    }
}
//---------------------------------------------------------------------------
TCoordonnee __fastcall TEtat::CalculPlaceVoulueEnBas( const TBande *Bd, bool bTakeBdPrec)const
{
  TCoordonnee cPlaceEnBas;
  try{
    TBande *b;
    WORD    Type = Bd->Type;

    PushResolutionAndPutEcran();
    cPlaceEnBas += DocOwner->Marges.Bottom;
    if( ( Type != e_EnTete) && ( Type != e_Pied) )
    {
        cPlaceEnBas.PixelsEcran = HauteurPied.PixelsEcran;  

        if( ( Type != e_ComplementPage) && ( Type != e_SautDePage))
        {
            b = GetBandeSpec(e_SautDePage);
            if( b) { b->HauteurForcee.Twips = -1; cPlaceEnBas.PixelsEcran += b->Hauteur.PixelsEcran;}

            if( ( Type != e_FinColonne) &&
                (bColonneEnCours) || ( Type <= e_DebutColonne))
            {
                b = GetBandeFinColonne();
                if( b) { b->HauteurForcee.Twips = -1; cPlaceEnBas.PixelsEcran += b->Hauteur.PixelsEcran;}
            }
            if( ( Type != e_FinColonne) && (Type != e_ReportFinDePage) &&
                ((bColonneEnCours &&
                 ( (Bd->Type == e_Principal) || (Bd->Type >= e_Utilisateur) ) ) ||
                 (!GetBandeDebColonne() && (Bd->operator < (MAKE_ETATNIVEAUBANDE( Niveau, 1, e_Fin)))))
                 || ( Type <= e_DebutColonne))
            {
                b = GetBandeReportFinPage();
                if( b) { b->HauteurForcee.Twips = -1; cPlaceEnBas.PixelsEcran += b->Hauteur.PixelsEcran;}
            }

            if( Type < e_DebutColonne)
            {
                b = GetBandeDetail()->LstBandesOwner->SearchBande( e_DebutColonne);
                if( b) { b->HauteurForcee.Twips = -1; cPlaceEnBas.PixelsEcran += b->Hauteur.PixelsEcran;}
            }
            if( Type < e_Principal)
            {
                b = GetBandeDetail();
                if( b) { b->HauteurForcee.Twips = -1; cPlaceEnBas.PixelsEcran += b->Hauteur.PixelsEcran;}
            }

        }
    }
    if( bTakeBdPrec && Bd->NumBandeUtilPrecedente)
    {
        b = Bd->LstBandesOwner->SearchBande( (TYPE_BANDE)(e_Utilisateur + Bd->NumBandeUtilPrecedente));
        if( b) { b->HauteurForcee.Twips = -1; cPlaceEnBas.PixelsEcran += b->Hauteur.PixelsEcran;}
    }

    PopResolution();
  }CATCH_EXCEPTION(TAGL)
  return cPlaceEnBas;
}

//---------------------------------------------------------------------------
void __fastcall TEtat::DebutDeSections( TObject* obj)
{
    TStringList *LstChampAReinitialiser = dynamic_cast<TStringList *>(obj);
    TBande      *BandeLimite = dynamic_cast<TBande *>(obj);
    TBande *b, *bADessiner;
// DEBUTS DE SECTIONS
    for( b = m_LstBandes->SearchBande( e_Principal);
            b;
         b = b->LstBandes? b->LstBandes->SearchBande( e_Principal) : NULL)
    {
        if( !LstChampAReinitialiser || (LstChampAReinitialiser->IndexOf( b->ChpRupture) != -1))
        {
            if( b->LstBandes && b->LstBandes->bRuptureVisible)
            {
                b->ValeurChpRupture = b->FieldRupture->AsString;
                bADessiner = b->LstBandes? b->LstBandes->SearchBande( e_Debut) : NULL;
                if( bADessiner &&
                     (!BandeLimite ||
                         ( (bADessiner != BandeLimite) &&
                           (bADessiner->Niveau <= BandeLimite->Niveau))))
                    bADessiner->Draw();
            }
        }
    }
}

void __fastcall TEtat::SetPortrait( bool b)
{
    if( b != m_bPortrait)
    {
        m_bPortrait = b;
        if( Glob->bConception)InvalideComposantsAttacheA(EmptyStr);
        _Invalidate();
        Modifie();
    }
}
//---------------------------------------------------------------------------

TBande* __fastcall TEtat::GetBandeDetail()const
{
    if( !m_BandeDetail)
    {
        TBande *b = SearchBande( e_Principal);
        while( b->LstBandes)
        {
            b = b->LstBandes->SearchBande( e_Principal);
        }
        (const_cast<TBande*>( m_BandeDetail)) = b;
    }
    return m_BandeDetail;
}

AnsiString  __fastcall TEtat::GetChampDB( const AnsiString &ChampDB)const
{
    try{
        TField *m_Field = m_BaseDeDonnee->FieldByName( ChampDB);
        ASSERT( m_Field->FieldName == ChampDB);
        return m_Field->AsString;
    }catch(...)
    {
        if( m_EtatAppelant) return m_EtatAppelant->GetChampDB( ChampDB);
        else return "ERREUR";
    }
}
//---------------------------------------------------------------------------
void __fastcall TEtat::OnErrorEvent( const AnsiString &Message)
{
    if( m_DocOwner->f_OnError)
    {
        if( m_CpChampEnCours)
            m_DocOwner->f_OnError( m_CpChampEnCours, AnsiString( "Erreur :\nChamp : ") +  m_CpChampEnCours->Nom + "\n" + Message);
        else if( m_BandeEnCours)
            m_DocOwner->f_OnError( m_BandeEnCours, AnsiString( "Erreur :\nBande : ") +  m_BandeEnCours->Titre + "\n" + Message);
        else m_DocOwner->f_OnError( this, Message);
    } else
    {
        AnsiString s;
        if( m_CpChampEnCours)
            s = AnsiString( "Erreur :\nChamp : ") +  m_CpChampEnCours->Nom + "\n" + Message;
        else if( m_BandeEnCours)
            s = AnsiString( "Erreur :\nBande : ") +  m_BandeEnCours->Titre + "\n" + Message;
        else s = Message;
        EICErreur( s);
    }
}
//---------------------------------------------------------------------------

bool __fastcall TEtat::OnVariableEvent(const AnsiString &Variable, TFieldType &Type, AnsiString &Valeur)
{
    bool Trouve = false;
#define NB_BANDES_POSSIBLES 2
    const TBande *b[NB_BANDES_POSSIBLES] = {BandeEnCours, GetBandeDetail()};
    b[0] = BandeEnCours; b[1] = GetBandeDetail();
    if( b[1] == b[0]) b[1] = NULL;
    for( int NumBande = 0; NumBande < NB_BANDES_POSSIBLES; NumBande++)
    {
        if( b[NumBande])
        {
            TCpChamp *CpChamp;
            for( int NumCp = 0;
                   NumCp < b[NumBande]->LstComposants->Count;
                 NumCp++)
            {
                CpChamp = dynamic_cast<TCpChamp*>( b[NumBande]->LstComposants->Items[NumCp]);
                if( CpChamp &&
                    (CpChamp != m_CpChampEnCours) && (CpChamp->Nom == Variable))
                {
                    Trouve = true;
                    Valeur = CpChamp->Texte;
                    Type = ((CpChamp->Format==tf_Monetaire)||(CpChamp->Format==tf_Numerique))? ftFloat:ftString;
                }
            }
        }
    }
    if( !Trouve && BaseDeDonnee)
    {
        TField *f = BaseDeDonnee->FindField( Variable);
        if( f)
        {
            Trouve = true;
            switch( f->DataType)
            {
                case  ftSmallint :
                case  ftInteger  :
                case  ftWord     :
                case  ftFloat    :
                case  ftBCD      :
                case  ftAutoInc  :
                case  ftLargeint :
                case  ftCurrency :
                case  ftBoolean  :
                    try{
                        if( !f->IsNull)
                            Valeur = f->AsVariant;
                        else
                            Valeur = D_NS;
                    }catch( ...)
                    {   Valeur = 0;  }
                    Type = ftFloat;
                    break;
/*                case  ftBoolean  :
                    {
                        TBooleanField *fb = (TBooleanField*)f;
                        Valeur = fb->AsFloat;
                        Type = ftFloat;
                    }break;*/
                default :
                    Valeur = f->AsString;
                    Type = ftString;
            }
        }
    }

    if( !Trouve && m_DocOwner->f_OnVariable)
    {
        Trouve = m_DocOwner->f_OnVariable( m_CpChampEnCours?(TObject*)m_CpChampEnCours:(TObject*)m_BandeEnCours, Variable, Type, Valeur);
    }
    return Trouve;
}

//---------------------------------------------------------------------------
//----------------------            BANDE             -----------------------
//---------------------------------------------------------------------------

__fastcall TBande::~TBande( )
{
    if( !DocOwner->bEnCoursDestruction)
    { /* Tous les composants ayant cette bande comme bande basse doivent changer */

    }
    Modifie();
    delete m_LstComposants; m_LstComposants = NULL;
    delete m_LstBandes;     m_LstBandes = NULL;
}
//---------------------------------------------------------------------------

const TCoordonnee   TBande::ms_margeYTitre = TCoordonnee(2*1440/96);
__fastcall TBande::TBande( TListOfBandes *Lst, TYPE_BANDE eType, TFlux *f): TMyObject( )
{
try{
//    m_bSautDePageAvant_Old = false;
    m_LstBandesOwner = Lst;
    m_Hauteur.PixelsY  = 150;
    m_HauteurCalc = -1;
    m_HauteurForceeMin.Twips = -1;
    m_HauteurForceeMax.Twips = -1;
    m_HauteurForcee.Twips = -1;
    m_eType = eType;
    m_LstBandes = NULL;
    m_bSautDePageAvant = false;
    m_bSautDePageApres = false;
    m_NumBandeUtilSuivante = 0;
    m_FieldRupture = NULL;
    m_bAutoLoop = false;
    m_RuptureInterieureAutorisee = true;
    m_PrisDansCalculColonne = true;

    if( f && f->Size)
    {
        m_Hauteur.Lit( f);
        if( m_Hauteur.PixelsY < 1) m_Hauteur.PixelsY = 1;
        f->Lit( m_ChpRupture);
        if( f->FileVersion >= FILE_VERSION( 0, 4))
        {
            f->Lit( m_bSautDePageAvant);
            f->Lit( m_bSautDePageApres);
        }
        if( f->FileVersion >= FILE_VERSION( 0, 5))
            f->Lit( m_NumBandeUtilSuivante);
        if( f->FileVersion >= FILE_VERSION( 1, 1))
            f->Lit( m_NumBandeUtilPrecedente);
        if( f->FileVersion >= FILE_VERSION( 1, 6))
        {
            f->Lit( m_EtatSuivant);
            f->Lit( m_FormuleVisible);
        }
        if( f->FileVersion >= FILE_VERSION( 1, 8))
            f->Lit( m_RuptureInterieureAutorisee);
        if( !m_ChpRupture.IsEmpty())
            m_LstBandes = new TListOfBandes( this, f);
//            m_NumBandeUtilSuivante = 0;
    }
    m_LstComposants = new TListOfComposants( this, f);
}catch( EDocException &e){throw;}
CATCH_EXCEPTION( TAGL);

}
//---------------------------------------------------------------------------

void __fastcall TBande::Enregistre( TFlux *f)const
{
    m_Hauteur.Enregistre( f);
    f->Ecrit( m_ChpRupture);
    f->Ecrit( m_bSautDePageAvant);
    f->Ecrit( m_bSautDePageApres);
    f->Ecrit( m_NumBandeUtilSuivante);
    f->Ecrit( m_NumBandeUtilPrecedente);
    f->Ecrit( m_EtatSuivant);
    f->Ecrit( m_FormuleVisible);
    f->Ecrit( m_RuptureInterieureAutorisee);
    if( !m_ChpRupture.IsEmpty())
        m_LstBandes->Enregistre( f);
    m_LstComposants->Enregistre( f);
}
//---------------------------------------------------------------------------
void __fastcall TBande::SetAutoLoop( bool b)
{
    if(  b && ((m_eType != e_Principal) || EtatOwner->BaseDeDonnee))
        throw EUser( TAGL, "l'autoloop ne doit pas être utilisé sur ce type de bande");
    else
        m_bAutoLoop = b;
}
//---------------------------------------------------------------------------

TListOfBandes* __fastcall TBande::GetLstBandesOwner( )const
{
    if( (m_LstBandesOwner == DocOwner->LstBandes) && DocOwner->CurEtat)
        return DocOwner->CurEtat->LstBandes;
    return m_LstBandesOwner;
}
bool __fastcall TBande::GetOwnerDocument()const
{
    return (m_LstBandesOwner == DocOwner->LstBandes);
}
//---------------------------------------------------------------------------

AnsiString __fastcall TBande::GetTitre() const
{
    AnsiString Titre;
    if( Type > e_Utilisateur)
    {
        Titre = AnsiString("Bande Utilisateur n°") + (Type - e_Utilisateur);
        return Titre;
    }else
        switch( Type)
        {
            case e_EnTete           : Titre = "En-tête de page";    break;
            case e_Debut            : Titre = "Début";              break;
            case e_DebutColonne     : return "Début de colonne";
            case e_ReportDebDePage  : return "Report début de page";
            case e_ReportFinDePage  : return "Report fin de page";
            case e_FinColonne       : return "Fin de colonne";
            case e_Principal        : Titre = "Corps";              break;
            case e_SautDePage       : return "Saut de page";
            case e_Fin              : Titre = "Fin";                break;
            case e_Pied             : Titre = "Pied de page";       break;
            case e_ComplementPage   : Titre = "Complement page";    break;
        }
    if( Niveau > 1)
        Titre += " de section (" + LstBandesOwner->BandeOwner->ChpRupture +")";
    else if( GetOwnerDocument())
        Titre += " général";
    else
        Titre += " d'état";
    return Titre;
}
//---------------------------------------------------------------------------
AnsiString __fastcall TBande::GetBubble(const TCoordonnee &X, const TCoordonnee &Y)const
{
    if( (X > TCoordonnee(0))                  &&
        (X < LargBarreGauche)                 &&
        (Y >= Top + ms_margeYTitre)           &&
        (Y <= Top + Hauteur - ms_margeYTitre)   )
    {
        return Titre;
    }
    return EmptyStr;
}
//---------------------------------------------------------------------------
void __fastcall TBande::EraseBkGnd(const TCoordonnee &cTop)
{    // Repaint le fond en blanc
    try{
    TCanvas *c = IsCanvasSupport();
    if( !c) return;
    TRect rc;   rc.Left  = 0;                           rc.Top = cTop.PixelsY;
                rc.Right = EtatOwner->Largeur.PixelsX;  rc.Bottom = cTop.PixelsY + Hauteur.PixelsY;
    if( EtatOwner && !EtatOwner->DocPdf.IsEmpty())
    {
        bool numPage = EtatOwner->DocPdf.SubString( EtatOwner->DocPdf.Length()-2, 3).UpperCase() == "CER" ||
                       EtatOwner->DocPdf.SubString( EtatOwner->DocPdf.Length()-2, 3).UpperCase() == "PDF" ;
        TCoorPoint pt;
 PushResolutionAndPutEcran();
        TCoorRect Marge; GetMarges( Marge);

        pt.x = 0;
        pt.y = 0;//-cTop;
  PopResolution();

        DrawImage( c, Marge, DocOwner->GetTruePathOfFile(EtatOwner->DocPdf), numPage?(TPicture*)EtatOwner->NumPagePdf:NULL, Et_Homo_Centre/*Et_Normal*/, &pt);
//        Pdf->Draw( c, EtatOwner->DocPdf, EtatOwner->NumPagePdf, Marge, &pt);
    }else if( Glob->bConception )//|| (m_Type == e_ComplementPage))
    {
        rc.Bottom = cTop.PixelsY + Hauteur.PixelsY;
        rc.Top = rc.Bottom - HAUTEUR_ENTRE_BANDES;
        c->Brush->Color = clBtnFace;
        c->FillRect( rc);

        rc.Bottom = rc.Top;
        rc.Top = cTop.PixelsY;
        c->Brush->Color = clWhite;
        c->Brush->Style = bsSolid;
        c->FillRect( rc);
    }
    }CATCH_EXCEPTION( TAGL);
}
//---------------------------------------------------------------------------

void __fastcall TBande::DessineMarge( const TCoordonnee &cTop)
{    // Marge
    TCanvas *c = IsCanvasSupport();
    if( !c) return;
    c->Pen->Style   = psSolid;
    c->Pen->Color   = clBtnFace;
    c->Pen->Width   = 1;

    TRect Marge;
    TCoorRect crMarge; GetMarges( crMarge);
    Marge = crMarge.RectPixels;
    Marge.Left   -= 1;
    Marge.Top    -= 1;
    Marge.Right  += 1;
    Marge.Bottom += 1;

    if( cTop.PixelsY != crMarge.Top.PixelsY)
    { // Marge Haut
        c->MoveTo( Marge.Left,  Marge.Top);
        c->LineTo( Marge.Right, Marge.Top);
    }
    if( (cTop + Hauteur).PixelsY!= crMarge.Top.PixelsY)
    { // Marge Bas
        c->MoveTo( Marge.Left,  Marge.Bottom);
        c->LineTo( Marge.Right, Marge.Bottom);
    }
        //Marge gauche
    c->MoveTo( Marge.Left,  Marge.Top);
    c->LineTo( Marge.Left,  Marge.Bottom+Glob->nRectifPourDessin);
        //Marge droite
    c->MoveTo( Marge.Right, Marge.Top);
    c->LineTo( Marge.Right, Marge.Bottom+Glob->nRectifPourDessin);
}
//---------------------------------------------------------------------------

void __fastcall TBande::DessineLigneSeparation(const TCoordonnee &cTop)
{   // Ligne de séparation
    TCanvas *c = IsCanvasSupport();
    if( !c) return;
    int nFinBande = cTop.PixelsY + m_Hauteur.PixelsY;
    c->Pen->Style   = psClear;
    c->Brush->Style = bsSolid;
    c->Brush->Color = clBtnFace;
    c->Rectangle( 0, nFinBande, EtatOwner->Largeur.PixelsX+Glob->nRectifPourDessin, nFinBande+HAUTEUR_ENTRE_BANDES+Glob->nRectifPourDessin);

    c->Brush->Style = bsClear;
    c->Pen->Width = 1;
    c->Pen->Style = psDashDotDot;
    c->Pen->Color = clBlack;
//    SetColor
//    DocOwner->CanvasSupport->MoveTo( 0, nFinBande + HAUTEUR_ENTRE_BANDES/2);
//    DocOwner->CanvasSupport->LineTo( DocOwner->Largeur.Pixels, nFinBande + HAUTEUR_ENTRE_BANDES/2);
}
//---------------------------------------------------------------------------
TField* __fastcall TBande::GetFieldRupture()
{
    if( Glob->bConception) return NULL;
    if( !m_FieldRupture)
    {
        m_FieldRupture = EtatOwner->BaseDeDonnee->FindField( m_ChpRupture);
    }
    return m_FieldRupture;
}
bool __fastcall TBande::TestHauteur( const TCoordonnee &cPlaceEnBas, bool &AttentionChpExtensibleSurPageSuivante,
                                     bool &bBdToDraw, bool bOnVientChangerUnePage)
{
  bool bReturn = false;
  try{
    TCoordonnee  HauteurMax;//(DocOwner->Hauteur - cPlaceEnBas);
    TCoorRect r;

    GetLimites( r);
    HauteurMax = (EtatOwner->Hauteur - cPlaceEnBas)-r.Top;

    if( EtatOwner->bFinPage && HauteurMax < 0)// on est en fin de page et y a plus de place???
    {
#ifdef _DEBUG
        throw EUser( TAGL, AnsiString( "Pb de hauteur [") + HauteurMax.PixelsY + "]");
#else
        EtatOwner->BasDerniereBande = EtatOwner->Hauteur - cPlaceEnBas - (r.Bottom - r.Top);
        GetLimites( r);
#endif
    }
    if( /*(r.Bottom - r.Top)*/Hauteur.PixelsR[Glob->ResolEcran] > HauteurMax.PixelsR[Glob->ResolEcran])
    {
        if( m_RuptureInterieureAutorisee &&
            (m_HauteurForceeMax > HauteurMax) && ( m_Hauteur < HauteurMax))
        {
              // rupture dans un champs extensible
            if( (m_HauteurForceeMin > HauteurMax) && ( m_Hauteur < HauteurMax))
                AttentionChpExtensibleSurPageSuivante = true;
            m_HauteurForceeMax.PixelsR[Glob->ResolEcran] = HauteurMax.PixelsR[Glob->ResolEcran]-1;
            if( m_HauteurForceeMin > m_HauteurForceeMax)
                AttentionChpExtensibleSurPageSuivante = true;
            m_HauteurForceeMin = m_HauteurForceeMax;
            bReturn = true;
        }else if( !bOnVientChangerUnePage)
        {
            EtatOwner->SautDePage( this, true);
            if( DocOwner->OnBande) bBdToDraw = DocOwner->OnBande( this);
            if(bBdToDraw)
            {
                EtatOwner->ValideDebutDePage( true);
                m_LstComposants->InitValeurs();
TRACEF( TAGL, "Autre appel à TestHauteur");
                TestHauteur( cPlaceEnBas, AttentionChpExtensibleSurPageSuivante, bBdToDraw, bOnVientChangerUnePage);
            }else
                EtatOwner->ValideDebutDePage( false);
            bReturn = true;
        }
    }
  }
  CATCH_Annul_TropDeCol_Abort( )
  CATCH_EXCEPTION( TAGL)
  return bReturn;
}
//---------------------------------------------------------------------------
void __fastcall TBande::DrawTitreBande(const TCoordonnee &cTop)
{      // Texte sur le coté
    TCanvas *c = IsCanvasSupport();
    if( !c) return;
    TRect rc; rc.Left = 0;                         rc.Top = cTop.PixelsY + ms_margeYTitre.PixelsY;
              rc.Right = LargBarreGauche.PixelsX;  rc.Bottom = cTop.PixelsY + m_Hauteur.PixelsY - ms_margeYTitre.PixelsY+Glob->nRectifPourDessin;
    c->Brush->Style = bsSolid;
    if( OwnerDocument)
    {
        c->Brush->Color = clInfoBk;
        c->Font->Color  = clInfoText;
    }else{
        c->Brush->Color = clActiveCaption;
        c->Font->Color  = clCaptionText;
    }
    c->FillRect( rc);

    TFontStyles ftStyle;
    ftStyle << fsBold;
    c->Font->Size = 8;
    c->Font->Style = ftStyle;
    EICFont *f = new EICFont();
    f->Assign(c->Font);
    DrawTexte( c, rc, NULL, NULL, f, Titre, (Text_Presentation)(Tx_HCentre | Tx_VCentre), 90);
    delete f;
}
//---------------------------------------------------------------------------
void __fastcall TBande::Draw( )
{
    if( DocOwner->Barre && DocOwner->Barre->Annule)
        throw EAnnulationImpression();
    TBande *ExBandeEnCours = NULL;
    if( !Glob->bConception)
    {
        ExBandeEnCours = EtatOwner->BandeEnCours;
        EtatOwner->BandeEnCours = this;
    }
    try{try{
        if( m_LstBandes && m_LstBandes->Count)
        {
            if( EtatOwner->BaseDeDonnee && !m_ChpRupture.IsEmpty() && m_LstBandes->bRuptureVisible)
            {
                m_ValeurChpRupture = FieldRupture->AsString;
            }
            m_LstBandes->Draw();
        }
        else
        {
            TBande  *bPrec = NULL, *bSuiv = NULL;
            bool AttentionChpExtensibleSurPageSuivante = false,
                 TiensElleEstEnCours = false,
                 bADessiner = true, bOnVientChangerUnePage  = false, bDebPageAValider = false, FirstBandeEtat = false/*, bPath =  false*/;
            m_PrisDansCalculColonne = true;

            if( ( m_eType != e_EnTete) && ( m_eType != e_Pied) )
            {
                if( EtatOwner->EtatNiveauType_FirstBandeToDraw )
                {
                    bADessiner = false;
                    if( EtatOwner->Niveau == GET_NIVETAT( EtatOwner->EtatNiveauType_FirstBandeToDraw))
                    {
                        TYPE_BANDE t = GET_TYPBANDE(EtatOwner->EtatNiveauType_FirstBandeToDraw);
                        if( t < e_Utilisateur)
                            bADessiner = (*this >= EtatOwner->EtatNiveauType_FirstBandeToDraw);
                        else{
                            __int64 i = MAKE_ETATNIVEAUBANDE( GET_NIVETAT(EtatOwner->EtatNiveauType_FirstBandeToDraw),
                                                              GET_NIVBANDE(EtatOwner->NiveauTypeBeforeUtil?EtatOwner->NiveauTypeBeforeUtil:EtatOwner->NiveauTypeAfterUtil),
                                                              GET_TYPBANDE(EtatOwner->NiveauTypeBeforeUtil?EtatOwner->NiveauTypeBeforeUtil:EtatOwner->NiveauTypeAfterUtil));
                            if( *this >= i)
                            {
                                if( EtatOwner->NiveauTypeBeforeUtil)
                                {
                                    bPrec = EtatOwner->LstBandes->SearchBande( t);
//                                    bPrec->Draw();
                                    EtatOwner->NiveauTypeBeforeUtil = 0;
                                    bADessiner = true;
                                }
                                if( EtatOwner->NiveauTypeAfterUtil)
                                {
                                    bSuiv = EtatOwner->LstBandes->SearchBande( t);
                                    EtatOwner->NiveauTypeAfterUtil = 0;
                                }
                            }
                        }
                    }
                }
                if( (bADessiner || bSuiv) && EtatOwner->EtatNiveauType_FirstBandeToDraw)
                {
                   // IndiceRepetition = EtatOwner->IndiceRepetPremBande;
                    EtatOwner->EtatNiveauType_FirstBandeToDraw = 0L; //Maintenant on imprime tout
                    EtatOwner->ForceSautDePage = false;
                    bDebPageAValider = EtatOwner->LstBandes->Count <= 1;
                    EtatOwner->SautDePage( this, bDebPageAValider);
                    bOnVientChangerUnePage = true;
                }
            }

            if( bADessiner)
            {
                if( !Glob->bConception )
                {
                    bool bSautdePage = EtatOwner->ForceSautDePage;
                    EtatOwner->ForceSautDePage = false;
                    if( ( m_eType != e_EnTete) && ( m_eType != e_Pied))
                    {
                        if( !bOnVientChangerUnePage &&
                            ( ( bSautdePage && !EtatOwner->bDebPage) ||
                              ( EtatOwner->BasDerniereBande.IsNegatif()) ))
                        {
                            EtatOwner->SautDePage( this, true);
                            bDebPageAValider=true;
                            bOnVientChangerUnePage = true;
                        }
                    }
                }
                m_LstComposants->AppliqueStyles();
                TCoordonnee WantedHeightMin, WantedHeightMax;
                if( !EtatOwner->DernBandeDessinee)
                {
                    FirstBandeEtat = true;
                    if( DocOwner->OnFirstBandeEtat) DocOwner->OnFirstBandeEtat( this);
                }
                m_HauteurForcee = -1;
                if( DocOwner->OnBande && !DocOwner->OnBande( this))
                {
                    if( m_eType == e_EnTete)
                        EtatOwner->BasDerniereBande = Top;
                    if( FirstBandeEtat && DocOwner->OnAfterFirstBandeInit) DocOwner->OnAfterFirstBandeInit( this);
                    if( bOnVientChangerUnePage)
                    {
                        TCanvas *c = IsCanvasSupport();
                        if( c)
                        {
                            if( bOnVientChangerUnePage)
                                EtatOwner->ValideDebutDePage( false);
                            if( !IsPrinting() || !Glob->EICPrinter->PDF)
                            {
                                c->Brush->Color = clWhite;
                                RECT r;
                                r.left   = DocOwner->Marges.Left.PixelsX;
                                r.top    = DocOwner->Marges.Top.PixelsY;
                                r.right  = EtatOwner->Largeur.PixelsX-DocOwner->Marges.Right.PixelsX + 1;
                                r.bottom = EtatOwner->Hauteur.PixelsY-DocOwner->Marges.Bottom.PixelsY + 1;
                                ::_FillRect( TAGL, c->Handle, &r, ::GetStockObject( WHITE_BRUSH) );
                            }
                        }
                        EtatOwner->BasDerniereBande = -2;
                    }
                    m_HauteurForcee = 0;
//TRACEF( TAGL, "[%-25.25s] OnBande FALSE", Titre.c_str());
                    goto finally;
                }
                if( bOnVientChangerUnePage && bDebPageAValider)
                {
                    EtatOwner->ValideDebutDePage( true);
                }
                TCoordonnee cPlaceEnBas = EtatOwner->CalculPlaceVoulueEnBas(this);
                if( !bPrec && m_NumBandeUtilPrecedente)
                    bPrec = EtatOwner->LstBandes->SearchBande( (TYPE_BANDE)(e_Utilisateur + m_NumBandeUtilPrecedente));
                if( m_NumBandeUtilSuivante)
                    bSuiv = EtatOwner->LstBandes->SearchBande( (TYPE_BANDE)(e_Utilisateur + m_NumBandeUtilSuivante));
            // GESTION DES EVENTUELS SAUTS DE PAGE AVANT DESSIN DE LA BANDE
                TCoorRect r;
                HRGN hClip;
                if( !Glob->bConception)
                {
                    if( (m_HauteurForceeMin.Twips != -1) && (m_eType != e_Pied))
                    {
                        m_HauteurForceeMin.Twips = -1;
                        m_HauteurForceeMax.Twips = -1;
                        m_LstComposants->NettoieComposantsAttacheA( Titre);
                    }
                    if( !bOnVientChangerUnePage && m_bSautDePageAvant && !EtatOwner->bDebPage)
                    {
                        EtatOwner->SautDePage( this, false);
                    }
                    GetLimites( r/*, true*/);
                    hClip = GetRegionInvalideInRect_ClipIt( r.RECTPixels);
                    if( !hClip) goto finally;

                    if( m_eType == e_Pied && EtatOwner->CpEndsInPied)
                    {
                        if( Top.Twips > EtatOwner->BasDerniereBande.Twips + 1)//PreviousBande->Top + PreviousBande->Hauteur)
                        {
                            LstBandesOwner->Add( e_ComplementPage);
                            TBande *bComplement = LstBandesOwner->SearchBande( e_ComplementPage);
                            bComplement->Hauteur = TCoordonnee::Pixels2TwipsY( r.Top.PixelsY - bComplement->Top.PixelsY);
                            GetLimites( r/*, true*/);
                            bComplement->Draw();
                            hClip = GetRegionInvalideInRect_ClipIt( r.RECTPixels);
                            if( !hClip) goto finally;
                            LstBandesOwner->Delete( e_ComplementPage);
                        }
                    }
                }else{
                    GetLimites( r/*, true*/);
                    hClip = GetRegionInvalideInRect_ClipIt( r.RECTPixels);
                    if( !hClip) goto finally;
                }


                bool bVisible = Glob->bConception || FormuleVisible.IsEmpty();
                if( !Glob->bConception && !FormuleVisible.IsEmpty())
                {
                    AnsiString s;
                    EtatOwner->Formule->Formule = FormuleVisible;
                    EtatOwner->Formule->Execute( s);
                    bVisible = (s != 0);
                }
                if( bVisible)
                {
#ifdef _DEBUG
                    if( IS_MACHINE_INFORMATICIEN())
                    {
                        char s[26];  strncpy( s, EtatOwner->Titre.c_str(), sizeof( s)-1); s[25] = '\0';
                        char s1[26]; strncpy( s1, Titre.c_str(), sizeof( s1)-1);          s1[25] = '\0';
                        TRACE( "%*c[%-25.25s] [%-25.25s] top[%.2lf] H[%.2lf] PlaceVoulue[%.2lf] hetat[%.2lf]", (EtatOwner->bDebPage||EtatOwner->bFinPage)?5:0, ' ', s, s1, /*EtatOwner->BasDerniereBande*/Top.Twips, Hauteur.Twips, cPlaceEnBas.Twips, EtatOwner->Hauteur.Twips);
                        //TRACE( "PIXELS %*c[%-25.25s] [%-25.25s] top[%.d] H[%.d] Bottom[%.d]", (EtatOwner->bDebPage||EtatOwner->bFinPage)?5:0, ' ', s, s1, EtatOwner->BasDerniereBande.Pixels, Hauteur.Pixels, r.Bottom.Pixels);
                        TRACE( "DixMm %*c[%-25.25s] [%-25.25s] top[%.d] H[%.d] Bottom[%.d] hetat[%.d]", (EtatOwner->bDebPage||EtatOwner->bFinPage)?5:0, ' ', s, s1, /*EtatOwner->BasDerniereBande*/Top.DixMm, Hauteur.DixMm, r.Bottom.DixMm, EtatOwner->Hauteur.DixMm);
                    }
#endif
                  // On regarde s'il faut forcer la hauteur (Cp extensible )
                    m_LstComposants->InitValeurs();

                    if( !Glob->bConception &&
                        m_LstComposants->WantedHeight(WantedHeightMin, WantedHeightMax, TiensElleEstEnCours) &&
                        (Hauteur < WantedHeightMax) || TiensElleEstEnCours)
                    {
                        m_HauteurForceeMax = WantedHeightMax;
                        m_HauteurForceeMin = WantedHeightMin;
                        m_LstComposants->NettoieComposantsAttacheA( Titre);
                    }
                    if( !TiensElleEstEnCours && bPrec)
                    {
                        cPlaceEnBas.PixelsY = cPlaceEnBas.PixelsY + bPrec->Hauteur.PixelsY;
                    }
                    if( !Glob->bConception)
                    {
                        if(( m_eType != e_EnTete) && ( m_eType != e_ComplementPage) && ( m_eType != e_Pied))
                        { // calcul de la hauteur max avec support ecran
                            bool bBdToDraw = true;
                            TestHauteur( cPlaceEnBas, AttentionChpExtensibleSurPageSuivante, bBdToDraw, bOnVientChangerUnePage);
                            if( !bBdToDraw)
                                goto finally;
                        }
                    }
                    GetLimites( r/*, true*/);
                    hClip = GetRegionInvalideInRect_ClipIt( r.RECTPixels);
                    if( !hClip) goto finally;

                    if( !TiensElleEstEnCours && bPrec)
                    {
                        if( Type < e_Utilisateur) EtatOwner->NiveauTypeBeforeUtil = MAKE_NIVEAUBANDE( Niveau, Type);
                        bPrec->Draw();
                        if( Type < e_Utilisateur) EtatOwner->NiveauTypeBeforeUtil = 0;
//                        cPlaceEnBas = EtatOwner->CalculPlaceVoulueEnBas(this);
                        GetLimites( r/*, true*/);
                        hClip = GetRegionInvalideInRect_ClipIt( r.RECTPixels);
                        if( !hClip) goto finally;
                    }

                    if( FirstBandeEtat && DocOwner->OnAfterFirstBandeInit) DocOwner->OnAfterFirstBandeInit( this);

#ifdef _DEBUG
//TRACE( "%*c[%-25.25s] [%-25.25s]  top[%.2lf] H[%.2lf] PlaceVoulue[%.2lf] hetat[%.2lf]", (EtatOwner->bDebPage||EtatOwner->bFinPage)?5:0, ' ', s, s1,EtatOwner->BasDerniereBande.Twips, Hauteur.Twips, cPlaceEnBas.Twips, EtatOwner->Hauteur.Twips);
#endif
                // DESSIN DE LA BANDE
                    EraseBkGnd( r.Top);

                    if( Glob->bConception)
                    {
                        DessineMarge( r.Top);
//                        DessineLigneSeparation( r.Top);
                        DrawTitreBande( r.Top);
                    }

                    if( !TiensElleEstEnCours)
                    {
                        m_LstComposants->Draw();
                        if( !m_ChpRupture.IsEmpty() && m_LstBandes->bRuptureVisible && EtatOwner->BaseDeDonnee)
                            m_ValeurChpRupture = FieldRupture->AsString;
                    }
                    else
                    {
                        m_LstComposants->DrawCpExtensibles();
                    }
                 // FIN DE LA BANDE
                    if( m_eType != e_Pied)
                        EtatOwner->BasDerniereBande = TCoordonnee::Pixels2Twips(r.Top.PixelsR[Glob->ResolEcran] + Hauteur.PixelsR[Glob->ResolEcran], Glob->ResolEcran);
                    if( (m_eType == e_EnTete) && (DocOwner->MargeHorsEntete != D_NS) && (EtatOwner->BasDerniereBande < DocOwner->MargeHorsEntete))
                        EtatOwner->BasDerniereBande = DocOwner->MargeHorsEntete;
                    EtatOwner->NbBandesSurLaPage = EtatOwner->NbBandesSurLaPage + 1;

                    if( !Glob->bConception && !TiensElleEstEnCours && m_PrisDansCalculColonne)
                    {
                        if( (m_eType == e_Principal) && (EtatOwner->LstCpColonne))
                        {
                            for( int i = 0; i < EtatOwner->LstCpColonne->Count; i++)
                            {
                                TCpChamp *Cp = (TCpChamp*)EtatOwner->LstCpColonne->Items[i];
                                if( !Cp->DansUneColonneViree())
                                    Cp->InitValeur(true);
                            }
                        }
                    }

                    if( AttentionChpExtensibleSurPageSuivante && !m_LstComposants->CpExtensiblesFinis())
                    {
                        if( !Glob->bConception) EtatOwner->DernBandeDessinee = this;
                        TCoordonnee h = m_Hauteur; m_Hauteur.DixMm = 0;
                        try{
                            EtatOwner->SautDePage( this, false);
                            Draw();
                        }__finally
                        {
                            m_Hauteur = h;
                        }
                    }
                    else if( m_eType == e_Principal)
                        m_IndiceRepetition++;

                }
                if( (m_HauteurForceeMin.Twips != -1) && (m_eType != e_Pied))
                {
                    m_HauteurForceeMin.Twips = -1;
                    m_HauteurForceeMax.Twips = -1;
                    m_LstComposants->NettoieComposantsAttacheA( Titre);
                }
                if( !Glob->bConception) EtatOwner->DernBandeDessinee = this;
            }
            if( !Glob->bConception && !AttentionChpExtensibleSurPageSuivante)
            {
                bool JaiDessineQqueChose = false;
                if( !m_EtatSuivant.IsEmpty()) {EtatOwner->DrawEtatSuivant( EtatOwner->OriginalFileName, m_EtatSuivant, true);JaiDessineQqueChose = true;}
                if( bSuiv)
                {
                    if( Type < e_Utilisateur) EtatOwner->NiveauTypeAfterUtil = MAKE_NIVEAUBANDE( Niveau, Type);
                    bSuiv->Draw();
                    if( Type < e_Utilisateur) EtatOwner->NiveauTypeAfterUtil = 0;
                    JaiDessineQqueChose = true;
                }
                if( (bADessiner || JaiDessineQqueChose) && m_bSautDePageApres)
                   EtatOwner->ForceSautDePage = true;// EtatOwner->SautDePage( NextBande);
            }
        }
        finally :
    }
    CATCH_Annul_TropDeCol_Abort( )
    CATCH_EXCEPTION( TAG( 50));
    }__finally
    {
        if( !Glob->bConception)
        {
            EtatOwner->BandeEnCours = ExBandeEnCours;
            EtatOwner->DernBandeDessinee = this;
            EtatOwner->bPremBandeEtat = false;
        }
    }

}
//---------------------------------------------------------------------------
void __fastcall TBande::Calculs()
{
    if( DocOwner->bEnCoursDestruction) return;
    if( m_LstBandes && m_LstBandes->Count)  m_LstBandes->Calculs();
    else if( m_LstComposants)               m_LstComposants->Calculs();
    m_PrevBande = CalcGetPrevBande();
    m_NextBande = CalcGetNextBande();
    if( !m_LstBandes && m_LstComposants)
    {
        bool ExisteUnComposantExtensible = false;
        for( int i = 0; i < m_LstComposants->Count && !ExisteUnComposantExtensible; i++)
        {
            TCpTexte *Cp = dynamic_cast<TCpTexte*>(m_LstComposants->Items[i]);
            if( Cp && ( Cp->Presentation & Tx_Extensible))
                ExisteUnComposantExtensible = ((TCpTexte *)m_LstComposants->Items[i])->BandeHt == this;
        }
        if( !Glob->bConception && !ExisteUnComposantExtensible)
            m_HauteurCalc = Hauteur;
    }
}
//---------------------------------------------------------------------------
bool __fastcall TBande::IsInBande( const TCoordonnee &Y)const
{
    int nTop = GetTop().PixelsY;
    return ( Y.PixelsY >= nTop) &&
           ( Y.PixelsY < (nTop + Hauteur.PixelsY-HAUTEUR_ENTRE_BANDES) );
}

TCoordonnee __fastcall TBande::GetTop( )const
{
    if( DocOwner->bEnCoursDestruction) return 0;
    if( !Glob->bConception)
    {
        switch( Type)
        {
            case e_EnTete       : return TCoordonnee::Pixels2Twips( DocOwner->Marges.Top.PixelsEcran, Glob->ResolEcran);
            case e_Pied         : return TCoordonnee::Pixels2Twips( EtatOwner->Hauteur.PixelsR[Glob->ResolEcran]
                                                                  - DocOwner->Marges.Bottom.PixelsR[Glob->ResolEcran]
                                                                  - Hauteur.PixelsR[Glob->ResolEcran],          Glob->ResolEcran);
            default             : return EtatOwner->BasDerniereBande > 0 ? EtatOwner->BasDerniereBande
                                                                         : EtatOwner->HauteurEntete;
        }
    }
    else
    {
        const TBande* bPrev = PreviousBande;
        if( bPrev)
            return TCoordonnee::Pixels2TwipsY(bPrev->Top.PixelsY + bPrev->Hauteur.PixelsY);// + TCoordonnee().AddPixels( 1);
        else
            return LstBandesOwner->Top;
    }
}
//---------------------------------------------------------------------------
void __fastcall TBande::ReprendHauteur( const TBande *b)
{
    m_HauteurCalc = b->m_HauteurCalc;
    m_HauteurForceeMax = b->m_HauteurForceeMax;
    m_HauteurCalc = b->m_HauteurCalc;

}
//---------------------------------------------------------------------------
TCoordonnee __fastcall TBande::GetHauteur( )const
{
    TCoordonnee H;
    if( !Glob->bConception && (m_HauteurCalc != -1) && (m_HauteurForcee < 0)) return m_HauteurCalc;

    if( m_LstBandes && m_LstBandes->Count)
    {
            H = m_LstBandes->Hauteur;
//            if( Glob->bConception)
//                Hauteur.AddPixels( m_LstBandes->Count);
    }
    else
    {
        if( !Glob->bConception)
        {
            TCoordonnee Forcage = m_HauteurForcee.IsNegatif()? m_HauteurForceeMax : m_HauteurForcee;
            if( EtatOwner)
            {
                TCoordonnee HOwner = EtatOwner->Hauteur - DocOwner->Marges.Top - DocOwner->Marges.Bottom;
                H = ( Forcage.IsNegatif())? min( m_Hauteur, HOwner): Forcage;
                if( Forcage > 0)
                    H += TCoordonnee::Pix( 1, Glob->ResolEcran);
            }else
                H = m_Hauteur;
        }else
        {
            H = m_Hauteur + TCoordonnee::Pixels2TwipsY( HAUTEUR_ENTRE_BANDES);
            // comptons aussi la ligne de séparation
            //H.Pixels += HAUTEUR_ENTRE_BANDES;
        }
    }
    return H;
}
//---------------------------------------------------------------------------
WORD  __fastcall TBande::GetNiveauValChange( )
{
    if( !EtatOwner->BaseDeDonnee) return 0;

    if( LstBandesOwner->BandeOwner)
    {
         WORD n = LstBandesOwner->BandeOwner->GetNiveauValChange();
         if( n) return n;
    }
    if( !m_ChpRupture.IsEmpty() &&
         m_LstBandes->bRuptureVisible &&
         m_ValeurChpRupture != FieldRupture->AsString)
        return Niveau;
    return (WORD)0;
}

void __fastcall TBande::GetLimitesHauteur( TCoordonnee &Mini, TCoordonnee &Maxi)const
{
    Mini.PixelsY = 1;
    Maxi.PixelsY = 1;

    TCoorRect rc, Marges, rcCp;
    GetMarges( Marges);
    rc.Left = LargBarreGauche + DocOwner->Marges.Left;  rc.Right = LargBarreGauche + EtatOwner->Largeur - DocOwner->Marges.Right;
    rc.Top  = Top;                                      rc.Bottom = Top + Hauteur;
    TList *ListeCp = new TList();
    EtatOwner->GetComposantsIn( ListeCp, rc, this, false);
        // la hauteur de l'entete doit être supérieure à la marge haute
        // la hauteur de la premiere bande doit être supérieure à la marge haute
    Mini = max( Marges.Top-rc.Top, TCoordonnee::PixY( 1));

    for( int i=0; i < ListeCp->Count; i++)
    {
        TComposant *Cp = (TComposant*)ListeCp->Items[i];
        if( !(Cp->CaracCp & car_HauteurBande) && (!(Cp->CaracCp & car_Graphic) || (!NextBande)))
        {
            Cp->GetTrueCoordonnees( rcCp);
            if( (Cp->CaracCp & car_ColleBas) && Cp->NomChpVertAssocie.IsEmpty())
                Mini = max( Mini, rcCp.Bottom - rcCp.Top + TCoordonnee::PixY(1));
            else
                Mini = max( Mini, rcCp.Bottom - rc.Top + TCoordonnee::PixY(1));
        }
    }
    delete ListeCp;

        // la hauteur du pied doit être supérieure à la marge basse
        // la hauteur de la dernière bande doit être supérieure à la marge basse
    if( rc.Bottom.PixelsY-1 != Marges.Bottom.PixelsY)
        Mini += (DocOwner->Marges.Bottom- rc.Top) - TCoordonnee::PixY( 1);

    Maxi = EtatOwner->HauteurPage ;//m_EtatOwner->Hauteur;//Hauteur + DocOwner->Hauteur - m_EtatOwner->Hauteur;
//    Maxi = m_EtatOwner->Hauteur;//Hauteur + DocOwner->Hauteur - m_EtatOwner->Hauteur;
//    TRACE( AnsiString( "%s   Mini [%d] Maxi [%d] Hauteur [%d]"),
//           ARRAYOFCONST((Titre.c_str(),Mini.Pixels,Maxi.Pixels,Hauteur.Pixels)));
}
//---------------------------------------------------------------------------

void __fastcall TBande::GetClipRectLimite( RECT &rc)const
{
    TCoordonnee Mini, Maxi;
    GetLimitesHauteur( Mini, Maxi);
    rc.left = 0;                 rc.right = EtatOwner->Largeur.PixelsX;
    rc.top = Top.PixelsY + Mini.PixelsY;
    rc.bottom = Top.PixelsY + Maxi.PixelsY;
}
//---------------------------------------------------------------------------

void __fastcall TBande::GetMarges( TCoorRect &Marge)const
{
    Marge.Left   = LargBarreGauche + DocOwner->Marges.Left;
    Marge.Top    = Top;
    Marge.Right  = EtatOwner->Largeur - DocOwner->Marges.Right;
    Marge.Bottom = Top + Hauteur;

    if( Glob->bConception)
        Marge.Bottom -= TCoordonnee::Pixels2TwipsY(HAUTEUR_ENTRE_BANDES);
/*    if( (m_eType == e_EnTete) || ((Marge.Top < DocOwner->Marges.Top) && (Marge.Bottom > DocOwner->Marges.Top)))
    { // Marge Haut
        Marge.Top += DocOwner->Marges.Top;
    }
    if( (m_eType == e_Pied) || ((Marge.Bottom) == EtatOwner->HauteurPage ) )
        Marge.Bottom -= DocOwner->Marges.Bottom;*/
    Marge.Bottom -= TCoordonnee::PixY( 1);
}

void __fastcall TBande::GetLimites( TCoorRect &rc/*, bool bWithBarreGauche*/)
{
    rc.Left = 0;
    rc.Right = EtatOwner->Largeur;// - LargBarreGauche;
    rc.Top = Top;
    rc.Bottom = rc.Top + Hauteur;
    if( IsPrinting( ))
    {
        rc.Left.PixelsX  += Glob->EICPrinter->PhysicalOffsetX+1;
        rc.Right.PixelsX -= Glob->EICPrinter->PhysicalOffsetX+1;
    }

/*    if( !bWithBarreGauche)
    {
        rc.Left  = rc.Left + LargBarreGauche + DocOwner->Marges.Left;
        rc.Right = rc.Right + LargBarreGauche - DocOwner->Marges.Right;
        if( ((m_Type == e_EnTete)&&!Niveau) || !Top.Pixels)
            rc.Top    = rc.Top + DocOwner->Marges.Top;
        if( ((m_Type == e_Pied)&&!Niveau)   || ((Top + m_Hauteur) == DocOwner->Hauteur))
            rc.Bottom = rc.Bottom - DocOwner->Marges.Bottom;
    }*/
}
//---------------------------------------------------------------------------
TBande* __fastcall TBande::CalcGetPrevBande( )const
{
    if( LstBandesOwner)
        return LstBandesOwner->PreviousBande(this);
    return NULL;
}
//---------------------------------------------------------------------------
TBande* __fastcall TBande::CalcGetNextBande( )const
{
    if( LstBandesOwner)
        return LstBandesOwner->NextBande(this);
    return NULL;
}
//---------------------------------------------------------------------------
void __fastcall TBande::SetHauteurForcee( const TCoordonnee &H)
{
    if( H > m_Hauteur)
    {
        TCoordonnee hMax = EtatOwner->Hauteur - Top - EtatOwner->CalculPlaceVoulueEnBas(this);
#ifdef _DEBUG
        if( H > hMax)
            throw EInvalidArgument( "la hauteur forcée est trop grande");
#endif
        m_HauteurForcee = min( H, hMax);
    }
#ifdef _DEBUG
    else
        throw EInvalidArgument( "la hauteur forcée est trop petite");
#endif

}
void __fastcall TBande::SetHauteurModifV1_11(const TCoordonnee &H)
{
    m_Hauteur = max( H, TCoordonnee::PixY( 1));
}

void __fastcall TBande::SetHauteur(const TCoordonnee &_nHauteur)
{
    TCoordonnee Mini, Maxi, nHauteur, AncDocHauteur;
    GetLimitesHauteur( Mini, Maxi);
    if( _nHauteur < Mini)  nHauteur = Mini;
    else if( _nHauteur > Maxi)  nHauteur = Maxi;
    else nHauteur = _nHauteur;

    if( nHauteur != m_Hauteur)
    {
        AncDocHauteur = EtatOwner->Hauteur;
        TCoorRect rDecal;
        rDecal.Left  = LargBarreGauche;
        rDecal.Top   = min( Hauteur, nHauteur)+Top;
        rDecal.Right = EtatOwner->Largeur;
        rDecal.Bottom   = max( Hauteur, nHauteur)+Top;

        m_Hauteur = nHauteur;
        if( m_eType != e_ComplementPage)
        {
            TList *ListeCp   = new TList();  // liste des composants modifiés
            EtatOwner->GetComposantsIn( ListeCp, rDecal, this, false);
            for( int i=0; i < ListeCp->Count; i++)
            {
                TComposant *Cp = (TComposant*)ListeCp->Items[i];
                if( Cp->CaracCp & car_Graphic)
                {
                    TCoorRect RectCp;
    //                m_Hauteur = AncDocHauteur;
                    Cp->GetTrueCoordonnees( RectCp);
    /*                RectCp.Top
                    m_Hauteur = nHauteur;
                    if( Cp->IsHautInBande( this) && (m_Hauteur < RectCp.Top) )
                        RectCp.Top.Pixels = Top.Pixels + m_Hauteur.Pixels + Glob->nRectifPourDessin;
                    if( RectCp.Bottom >  )*/

                    Cp->SetBounds( RectCp.Left,  RectCp.Top - Cp->BandeHt->Top,
                                   RectCp.Right, RectCp.Bottom - Cp->BandeBs->Top);
                }
            }
            delete ListeCp;
        }
        if( Glob->bConception)
        {
            _Invalidate( 0, 0, EtatOwner->Largeur.PixelsX, Top.PixelsY + max(EtatOwner->Hauteur.PixelsY, AncDocHauteur.PixelsY));
            if( EtatOwner->Hauteur.PixelsY < AncDocHauteur.PixelsY)
            {
                HRGN h = ::_CreateRectRgn( TAGL, 0, EtatOwner->Hauteur.PixelsY, EtatOwner->Largeur.PixelsX, EtatOwner->Hauteur.PixelsY);
                DocOwner->EffaceRegion( h);
                ::_DeleteObject( TAGL, h);
            }
        }
        Modifie();
        EtatOwner->InvalideComposantsAttacheA(Titre);
    }
/*
        TList *l = new TList();  // liste des composants modifiés
        TList *lHaut = new TList();
        RECT rResul, rDecal = { DocOwner->LargBarreGauche.Pixels, min( m_Hauteur.Pixels, nHauteur.Pixels)+Top.Pixels,
                                DocOwner->Largeur.Pixels,         max( m_Hauteur.Pixels, nHauteur.Pixels)+Top.Pixels};
        if( LstComposants)
        {
            for( int i=0; i < LstComposants->Count; i++)
            {
                TComposant *Cp = (TComposant*)DocOwner->CurEtat->ListeCp->Items[i];
                TCoorRect RectCp;
                Cp->GetTrueCoordonnees( RectCp);
                RECT rCp = RectCp.RECTPixels;
                    // au cas ou le composant veuille s'invalider entièrement ???
                if( ::IntersectRect( &rResul, &rDecal, &rCp))
                {
                    TCoorRect cr; cr.RECTPixels = rResul;
                    Cp->InvalidateR( cr);
                    l->Add( (TObject*)Cp);
                    lHaut->Add( (void*)MAKELPARAM( rCp.top, rCp.bottom));
                    Cp->InvalidateSelect( );
                }
            }
        }
//        TCoordonnee cUn, AncHauteur = m_Hauteur; cUn.Pixels=1;
//        DocOwner->ScrollBasBitmap( Top + m_Hauteur , nHauteur - m_Hauteur, BmpSupport);

        m_Hauteur = nHauteur;
        InvalidateAll();

        for( int i=0; i < l->Count; i++)
        {
            TComposant *Cp = (TComposant*)l->Items[i];
            Cp->Invalidate( );
            TCoorRect RectCp;
            Cp->GetTrueCoordonnees( RectCp);
            RECT rCp = RectCp.RECTPixels;
            if( ((Cp->BandeHtG == this) || (Cp->BandeBsD == this)) &&
                (( Top + Cp->PointHtG.y) > ( Top + m_Hauteur) )       )
            {
                TCoordonnee top;    top.Pixels    = Top.Pixels + m_Hauteur.Pixels + 1;
                TCoordonnee bottom; bottom.Pixels = HIWORD( (long)lHaut->Items[i]);
                Cp->SetBounds( RectCp.Left - DocOwner->LargBarreGauche,  top,
                               RectCp.Right - DocOwner->LargBarreGauche, bottom);
                bottom = top;  top = Cp->BandeHtG->Top;
            }
            Cp->InvalidateSelect( );
        }
        Modifie();
        delete l;
        delete lHaut;
    }*/
}
//---------------------------------------------------------------------------
void __fastcall TBande::InvalidateAll( )
{
    RECT r = { 0,                     Top.PixelsY,
               EtatOwner->Largeur.PixelsX, Top.PixelsY + m_Hauteur.PixelsY + Glob->nRectifPourDessin};
    TCoorRect cr; cr.RECTPixels = r;
    _Invalidate( cr);
}
//---------------------------------------------------------------------------
void __fastcall TBande::Invalidate( )
{
    RECT r = { (LargBarreGauche + DocOwner->Marges.Left).PixelsX,
               max( Top.PixelsY, DocOwner->Marges.Top.PixelsY),
               EtatOwner->Largeur.PixelsX - DocOwner->Marges.Right.PixelsX,
               min( Top.PixelsY + m_Hauteur.PixelsY + Glob->nRectifPourDessin, EtatOwner->Hauteur.PixelsY - DocOwner->Marges.Bottom.PixelsY) };
    TCoorRect cr; cr.RECTPixels = r;
    _Invalidate( cr);
}

//---------------------------------------------------------------------------
void __fastcall TBande::SupprimeComposant( TComposant *Cp)
{
    m_LstComposants->Delete( Cp);
}
//---------------------------------------------------------------------------
TComposant* __fastcall TBande::InsereComposant( Carac_Composant wType, const TCoordonnee &X, const TCoordonnee &Y)
{
    return( m_LstComposants->Add( wType, X, Y));
}
//---------------------------------------------------------------------------
WORD __fastcall TBande::GetNiveau( )const
{
    if( m_eType >= e_Utilisateur)
        return GET_NIVBANDE( EtatOwner->NiveauTypeBeforeUtil);
    if( LstBandesOwner)
    {
        if( LstBandesOwner->BandeOwner)
            return  (WORD)(LstBandesOwner->BandeOwner->Niveau+1);
        else return 1;
    }
    else
        return 0;
}
//---------------------------------------------------------------------------

void __fastcall TBande::SetChpRupture( const AnsiString &ChpRupture)
{
    if( ChpRupture != m_ChpRupture)
    {
        m_ChpRupture = ChpRupture;
        Modifie();
        if( m_ChpRupture.IsEmpty())
        {
            if( m_LstBandes)
            {
                delete m_LstBandes;
                m_LstBandes = NULL;
            }
        }
        else
            if( !m_LstBandes)
                m_LstBandes = new TListOfBandes( this);
        if( EtatOwner) EtatOwner->Nettoie();
    }
}
//---------------------------------------------------------------------------

void __fastcall TBande::Nettoie( )
{
    m_HauteurCalc      = -1;
    m_ValeurChpRupture = EmptyStr;
    m_FieldRupture     = NULL;
    m_HauteurForceeMin = -1;
    m_HauteurForceeMax = -1;

//    m_bSautDePageAvant_Old = -1;
    if( m_LstBandes) m_LstBandes->Nettoie();
    if( m_LstComposants) m_LstComposants->Nettoie();
}
//---------------------------------------------------------------------------
void __fastcall TBande::RefreshValRupture( )
{
    if( !m_ChpRupture.IsEmpty() && m_LstBandes->bRuptureVisible && EtatOwner->BaseDeDonnee)
        m_ValeurChpRupture = FieldRupture->AsString;
    if( m_LstBandes) m_LstBandes->RefreshValRupture();
}
//---------------------------------------------------------------------------
TCpChamp *__fastcall TBande::GetCpChamp( const AnsiString &s)const
{
    if( m_LstComposants) return m_LstComposants->GetCpChamp(s);
    else                 return NULL;
}
//---------------------------------------------------------------------------
TCpTableau *__fastcall TBande::GetCpTableau( const AnsiString &s)const
{
    if( m_LstComposants) return m_LstComposants->GetCpTableau(s);
    else                 return NULL;
}
//---------------------------------------------------------------------------
void __fastcall TBande::RecupereProprietesComposants( TBande *b)
{
    if( b && b != this)
    {
        for( int i = 0; i < b->m_LstComposants->Count; i++)
        {
            m_LstComposants->Add( b->LstComposants->Items[i]);
        }
        b->LstComposants->TList::Clear();

          // Définition globale d'une bande
        m_Hauteur       = b->m_Hauteur;
//        m_Type          = b->Type;
//        m_ChpRupture    = b->ChpRupture;
    }
}
//---------------------------------------------------------------------------

TComposant* __fastcall TBande::GetComposant( const AnsiString &s)const
{
    if( m_LstBandes && m_LstBandes->Count)  return m_LstBandes->GetComposant( s);
    else if( m_LstComposants)               return m_LstComposants->GetComposant( s);
    return NULL;
}
//---------------------------------------------------------------------------

void        __fastcall TBande::GetComposants( enum TypesComposants TypeCp, TStrings *LstCp)const
{
    if( m_LstBandes && m_LstBandes->Count)  m_LstBandes->GetComposants( TypeCp, LstCp);
    else if( m_LstComposants)               m_LstComposants->GetComposants( TypeCp, LstCp);
}
//---------------------------------------------------------------------------
void __fastcall TBande::InvalideComposantsAttacheA( const AnsiString &ChpAttache)
{
    if( m_LstBandes && m_LstBandes->Count)  m_LstBandes->InvalideComposantsAttacheA( ChpAttache);
    else if( m_LstComposants)               m_LstComposants->InvalideComposantsAttacheA( ChpAttache);
}
//---------------------------------------------------------------------------
void __fastcall TBande::NettoieComposantsAttacheA( const AnsiString &ChpAttache)
{
    if( m_LstBandes && m_LstBandes->Count)  m_LstBandes->NettoieComposantsAttacheA( ChpAttache);
    else if( m_LstComposants)               m_LstComposants->NettoieComposantsAttacheA( ChpAttache);
}
//---------------------------------------------------------------------------
bool  __fastcall TBande::operator  < (__int64 EtatNiveauType)const
{
    DWORD       EtatNiveau  = GET_NIVETAT( EtatNiveauType);
    WORD        NiveauBande = GET_NIVBANDE(EtatNiveauType);
    TYPE_BANDE  eTypeBande  = GET_TYPBANDE(EtatNiveauType);
    if( operator!= (EtatNiveauType) && (EtatOwner->Niveau == EtatNiveau))
    {
        if( m_eType <= e_Principal)
        {
    /*        if( Niveau > bNiveau )          return false;
            else if( Niveau >= bNiveau )    return m_Type < bType;
            else if( Niveau < bNiveau )     return m_Type <= bType;*/
            if( eTypeBande > e_Principal)       return true;
            else if( Niveau < NiveauBande )     return true;
            else if( Niveau == NiveauBande )    return m_eType < eTypeBande;
            else if( Niveau > NiveauBande )     return false;//m_Type < TypeBande;
        }
        else if ( m_eType > e_Principal)
        {
    /*        if( Niveau < bNiveau )          return true;
            else if( Niveau == bNiveau )    return m_Type < bType;
            else if( Niveau > bNiveau )     return m_Type < bType;*/
            if( eTypeBande < e_Principal)       return false;
            else if( Niveau < NiveauBande )     return false;
            else if( Niveau == NiveauBande )    return m_eType < eTypeBande;
            else if( Niveau > NiveauBande )     return true;//m_Type <= TypeBande;
        }
        else                                return (Niveau < NiveauBande);
    }else
        return EtatOwner->Niveau < EtatNiveau;
    return false;
}

bool  __fastcall TBande::operator  > (__int64 EtatNiveauType)const
{
    return !operator< (EtatNiveauType) && !operator== (EtatNiveauType);
}
bool  __fastcall TBande::operator  == (__int64 EtatNiveauType)const
{
    DWORD       EtatNiveau  = GET_NIVETAT( EtatNiveauType);
    WORD        NiveauBande = GET_NIVBANDE(EtatNiveauType);
    TYPE_BANDE  eTypeBande  = GET_TYPBANDE(EtatNiveauType);
    return ( (EtatOwner->Niveau == EtatNiveau) && (Niveau == NiveauBande) && (m_eType == eTypeBande));
}
bool  __fastcall TBande::operator  != (__int64 EtatNiveauType)const
{
    return !operator==( EtatNiveauType);
}

//---------------------------------------------------------------------------
bool  __fastcall TBande::operator  < (const TBande &b)const
{
    return *this < MAKE_ETATNIVEAUBANDE( EtatOwner->Niveau, b.Niveau, b.Type);
}

bool  __fastcall TBande::operator  > (const TBande &b)const
{
    return *this > MAKE_ETATNIVEAUBANDE( EtatOwner->Niveau, b.Niveau, b.Type);
}
bool  __fastcall TBande::operator  == (const TBande &b)const
{
    return *this == MAKE_ETATNIVEAUBANDE( EtatOwner->Niveau, b.Niveau, b.Type);
}


//---------------------------------------------------------------------------
//----------------            LISTES DE BANDES             ------------------
//---------------------------------------------------------------------------
int __fastcall SortBandes( void* Bande1, void* Bande2)
{
    return ((TBande*)Bande1)->Type - ((TBande*)Bande2)->Type;
}
//---------------------------------------------------------------------------

__fastcall TListOfBandes::~TListOfBandes( )
{
    while( TList::Count)
    {
         delete (TBande*)( ((TList*)this)->Items[0]);
         TList::Delete( 0);
    }
    if( m_TrueList) delete m_TrueList;
}
//---------------------------------------------------------------------------

__fastcall TListOfBandes::TListOfBandes( TObject *Owner, TFlux *f):TList()
{
try{
    m_DocOwner = NULL;
    m_EtatOwner = NULL;
    TBande *b;
    m_bRuptureVisible= true;
    m_Owner = Owner;
    m_TrueList = new TList();
    if( !f || !f->Size)
    {
    }
    else
    {
        TYPE_BANDE    eType;
        int dw, dwOffsetFin = f->Position;  f->Lit( dw);  dwOffsetFin += dw;
        while( (f->Position != f->Size) && (dwOffsetFin != f->Position))
        {
            WORD w;
            f->Lit( w); eType = (TYPE_BANDE)w;
            b = new TBande( this, eType, f);
//          ATTENTION AUX BANDES COLONNES : ELLES NE DOIVENT PAS ETRE AUTRE PART QUE SUR LA BANDE DETAIL OU SUR L'ETAT
//            if( ((b->Type == e_DebutColonne) || (b->Type == e_FinColonne))
//                && m_BandeOwner &&
//                continue;
            TList::Add( b);
        }
        TList::Sort( SortBandes);
    }

    if( !TList::Count /*&& !m_BandeOwner*/ && EtatOwner /*&& DocOwner*/)
    {
        TList::Add( new TBande( this, e_Principal, f) );
    }
}catch( EDocException &e){throw;}
CATCH_EXCEPTION( TAGL);

}
TDocument* __fastcall TListOfBandes::GetDocOwner( )const
{
    if( !Glob->bConception && m_DocOwner)
        return m_DocOwner;
    TDocument **d = (TDocument**)&m_DocOwner;
    *d = dynamic_cast<TDocument*>(m_Owner);
    if( *d)                return *d;
    else if( EtatOwner)    return *d = EtatOwner->DocOwner;
    ASSERT( BandeOwner);
    return *d = BandeOwner->DocOwner;
}
TEtat*     __fastcall TListOfBandes::GetEtatOwner( )const
{
    if( !Glob->bConception && m_EtatOwner)
        return m_EtatOwner;
    TEtat **e = (TEtat**)&m_EtatOwner;
    *e = dynamic_cast<TEtat*>(m_Owner);
    if( *e)                return *e;
    else if( BandeOwner)   return *e = BandeOwner->EtatOwner;
    ASSERT( DocOwner);
    return *e = DocOwner->EtatEnCours;
}
TBande*    __fastcall TListOfBandes::GetBandeOwner( )const
{
    return dynamic_cast<TBande*>(m_Owner);
}
//---------------------------------------------------------------------------

void __fastcall TListOfBandes::Enregistre( TFlux *f)const
{
    int nOffsetDebut = f->Position;   f->Ecrit( (int)0);
    for( int i = 0; i < TList::Count; i++)
    {
        TBande *b = (TBande*)( ((TList*)this)->Items[i]);
        f->Ecrit( (WORD)(b->Type));
        b->Enregistre( f);
    }
    int nOffsetFin = f->Position;  f->Position = nOffsetDebut;
    f->Ecrit( (int)nOffsetFin-nOffsetDebut);
    f->Position = nOffsetFin;
}
//---------------------------------------------------------------------------
void __fastcall TListOfBandes::Copy( const TListOfBandes * lst)
{
}
//---------------------------------------------------------------------------
void __fastcall TListOfBandes::Draw( )
{
    TBande* b;
    try{
        int Niveau = BandeOwner? BandeOwner->Niveau : 0;
        if( m_bRuptureVisible)
        {
            if( !Niveau || !EtatOwner->BaseDeDonnee || (!EtatOwner->BaseDeDonnee->Eof && EtatOwner->nbEnreg))
            {
                b = SearchBande( e_Debut);
                if( b)
                    b->Draw();
            }
        }
//        if( Glob->bConception || (!EtatOwner->BaseDeDonnee || (EtatOwner->nbEnreg != 0)))
// dans etat de rapprochement, on a besoin de l'entête de colonne quand on a pas de donnes
        {
            TBande *bDebCol = SearchBande( e_DebutColonne),
                   *bFinCol = SearchBande( e_FinColonne);
        //            if( m_bRuptureVisible)
            {
                if( bDebCol)  bDebCol->Draw();
                if( bDebCol || bFinCol)
                    EtatOwner->bColonneEnCours = true;

            }
            if( Glob->bConception)
            {
                b = SearchBande( e_ReportDebDePage);
                if( b) b->Draw();
            }
            b = SearchBande( e_Principal);
            if( b)
            {
                if( !Glob->bConception && EtatOwner->GetNiveauBandeBasse() == Niveau)
                {
                    if( !EtatOwner->EtatNiveauType_FirstBandeToDraw)
                        b->IndiceRepetition = 0;
                    if( !EtatOwner->BaseDeDonnee) b->bAutoLoop = false;
                    while( !EtatOwner->BaseDeDonnee || (!EtatOwner->BaseDeDonnee->Eof && EtatOwner->nbEnreg))
                    {
                        b->Draw();
                        if( EtatOwner->BaseDeDonnee)   EtatOwner->BaseDeDonnee->Next();
                        else if( b->bAutoLoop == true) {EtatOwner->OnDataChange(NULL, NULL);continue; }
                        else                           break;
                    }
                }
                else b->Draw();
            }
   //         if( m_bRuptureVisible)
            {
                if( Glob->bConception)
                {
                    b = SearchBande( e_ReportFinDePage);
                    if( b)  b->Draw();

                    b = SearchBande( e_SautDePage);
                    if( b)  b->Draw();
                }

                if( bFinCol || bDebCol)
                    EtatOwner->bColonneEnCours = false;
                if( bFinCol)  bFinCol->Draw();
            }
        }

        if( m_bRuptureVisible)
        {
            if( !Niveau || !EtatOwner->BaseDeDonnee || /*!*/(EtatOwner->BaseDeDonnee->Eof && EtatOwner->nbEnreg))
            {
                b = SearchBande( e_Fin);
                if( b && (b != EtatOwner->DernBandeDessinee))
                    b->Draw();
            }

            if( Glob->bConception)
            {
                WORD n = 1;
                do{
                    b = SearchBande( (TYPE_BANDE)(e_Utilisateur + n));
                    if( b)  b->Draw();
                    n++;
                }while( b);
            }
        }
        if( !BandeOwner && EtatOwner->EtatSuivant)
        {
            TBande *b1 = EtatOwner->BandeEnCours;
            ASSERT( b1 == NULL);
            EtatOwner->BandeEnCours = EtatOwner->DernBandeDessinee;
            if( EtatOwner->EspaceApres.Twips && (EtatOwner->BasDerniereBande != -1))
                EtatOwner->BasDerniereBande = EtatOwner->BasDerniereBande + EtatOwner->EspaceApres;
			try
            {
            EtatOwner->DrawEtatSuivant( EtatOwner->EtatSuivant);
			}CATCH_Annul_TropDeCol_Abort()
            CATCH_EXCEPTION( TAGL)
            EtatOwner->BandeEnCours = NULL;
        }else if( !BandeOwner &&
                  (!EtatOwner->EtatAppelant || (EtatOwner->EtatAppelant->EtatSuivant == EtatOwner)) ) // n'est pas un etat dans un autre
            EtatOwner->SautDePage( NULL, false, false);
        if( !BandeOwner && !EtatOwner->NumberOfPage && // liste de bandes de l'etat
            !EtatOwner->EtatSuivant && // pas d'etat apres
            (!EtatOwner->EtatAppelant || (EtatOwner->EtatAppelant->EtatSuivant == EtatOwner)) ) // n'est pas un etat dans un autre
            EtatOwner->NumberOfPage = EtatOwner->CurrentPage;

    }CATCH_Annul_TropDeCol_Abort()
    CATCH_EXCEPTION( TAG( 60))
}
//---------------------------------------------------------------------------
void __fastcall TListOfBandes::Calculs( )
{
    for( int i = 0; i < Count; i++)
    {
        Bandes[ i]->Calculs();
    }
}
//---------------------------------------------------------------------------
TList* __fastcall TListOfBandes::GetTrueList( ) const
{
//    if( !(dynamic_cast<TEtat*>m_Owner) && !BandeOwner && DocOwner && DocOwner->LstBandes)
    if( dynamic_cast<TEtat*>(m_Owner) && !BandeOwner && DocOwner && DocOwner->LstBandes)
    {   // première liste de bande (niveau de l'état)
        if( !m_TrueList->Count || Glob->bConception)
        {
            bool bEntete = false,    bPied = false;
            TBande *b;
            m_TrueList->Clear();
            for( int i = 0; i < TList::Count; i++)
            {
                b = (TBande*)(const_cast<TListOfBandes*>(this)->Items[i]);
                if( b->Type == e_EnTete) bEntete = true;
                if( b->Type == e_Pied)   bPied = true;
                m_TrueList->Add( (void*)b);
            }
            if( !bEntete)
            {
                b = DocOwner->LstBandes->SearchBande( e_EnTete);
                if( b) m_TrueList->Insert( 0, (void*)b);
            }
            if( !bPied)
            {
                b = DocOwner->LstBandes->SearchBande( e_Pied);
                if( b) m_TrueList->Add( (void*)b);
            }
        }
        // Normalement la liste est toujours triée
        return m_TrueList;
    }
    return (TList*)this;
}
//---------------------------------------------------------------------------
int  __fastcall TListOfBandes::GetCount()const
{
    return GetTrueList( )->Count;
}
//---------------------------------------------------------------------------
TBande* __fastcall TListOfBandes::Get(int Index)const
{
    return (TBande*)(GetTrueList( )->Items[ Index]);
}
int __fastcall TListOfBandes::IndexOf( const TBande *Bande)const
{
    return GetTrueList( )->IndexOf( (void*)Bande);
}
//---------------------------------------------------------------------------
void __fastcall TListOfBandes::Add( TYPE_BANDE eType)
{
    TBande *b = SearchBande( eType);
    if( !b || (b->LstBandesOwner != this) || b->OwnerDocument)
    {
        TList::Add( new TBande( this, eType));
        m_TrueList->Clear();
        TList::Sort( SortBandes);
        DocOwner->Modifie();
        if( EtatOwner)
            EtatOwner->_Invalidate( TCoordonnee(), EtatOwner->Top, EtatOwner->Largeur, EtatOwner->Top + EtatOwner->Hauteur);
        else if( DocOwner)
            DocOwner->_Invalidate( 0, 0, DocOwner->Largeur.PixelsX, DocOwner->Hauteur.PixelsY);
    }
}
//---------------------------------------------------------------------------

void __fastcall TListOfBandes::Delete( TYPE_BANDE eType)
{
    TBande* b = SearchBande( eType);
    if( b && (b->LstBandesOwner == this))
    {
        if( EtatOwner)
        {
            TListOfBandes *Lst = EtatOwner->LstBandes;
            do{
                for( int i = 0; i < Lst->Count; i++)
                {
                    TListOfComposants *LstCp = Lst->Bandes[ i]->LstComposants;
                    if( LstCp)
                    {
                        for( int j = 0; j < LstCp->Count; j++)
                        {
                            LstCp->Items[ j]->ControleApresSuppression( b);
                        }
                    }
                }
                Lst = Lst->SearchBande( e_Principal)->LstBandes;
            }while( Lst);
        }
        TList::Delete( TList::IndexOf( b));
        m_TrueList->Clear();
        delete b;
        DocOwner->Modifie();
        if( EtatOwner)
            EtatOwner->_Invalidate( TCoordonnee(), EtatOwner->Top, EtatOwner->Largeur, EtatOwner->Top + EtatOwner->Hauteur);
        else if( DocOwner)
            DocOwner->_Invalidate( 0, 0, DocOwner->Largeur.PixelsX, DocOwner->Hauteur.PixelsY);
   }
}
//---------------------------------------------------------------------------

TBande* __fastcall TListOfBandes::SearchBande( TYPE_BANDE eType)const
{
  try{
    for( int i = 0; i < Count; i++)
    {
         if( eType == Bandes[ i]->Type)
            return Bandes[ i];
    }
  }CATCH_EXCEPTION(TAGL)
    // ensuite étudions le cas particulier NIVEAU 0 Entete ou pied
    // Au cas ou il y ai un truc au niveau du doc
/*    if( !m_BandeOwner && m_EtatOwner && m_DocOwner->LstBandes)
    {
        return m_DocOwner->LstBandes->SearchBande( Type);
    }*/
  return NULL;
}
//---------------------------------------------------------------------------

bool __fastcall TListOfBandes::Included( const TBande *Bande)const
{
    return( IndexOf( Bande) != -1);
}
//---------------------------------------------------------------------------

TBande* __fastcall TListOfBandes::PreviousBande( const TBande *Bande)const
{
    TBande* b;
    int Index = IndexOf( Bande);
    try{
        if(      Index < 0)   b = NULL;
        else if( Index == 0)  b = BandeOwner? BandeOwner->PreviousBande : NULL;
        else
        {
/*            if( !m_BandeOwner && !m_EtatOwner)
                b = m_DocOwner->CurEtat->LstBandes->LastBande();
            else*/
                b = Bandes[ Index-1];
        }

        if( b && b->LstBandes)
            b = (TBande*)b->LstBandes->Last();
    }
    catch(...)
    {
        b = NULL;
    }
    return b;
}
//---------------------------------------------------------------------------

TBande* __fastcall TListOfBandes::NextBande( const TBande *Bande)const
{
    TBande* b;
    int Index = IndexOf( Bande);
    try{
        if( Index < 0)                                b = NULL;
        else if( Index == Count-1 )
        {
            bool bCanRecommence = false;
            if( BandeOwner)
                bCanRecommence = BandeOwner->bAutoLoop || !BandeOwner->ChpRupture.IsEmpty();

            if( Glob->bConception || !bCanRecommence)
                b = BandeOwner? BandeOwner->NextBande : NULL;
            else
                b = Bandes[0];
        }else
        {
/*            if( !m_BandeOwner && !m_EtatOwner)
                b = m_DocOwner->CurEtat->LstBandes->FirstBande();
            else  */
                b = Bandes[ Index+1];
        }
//        if( b && b->LstBandes)
//            b = (TBande*)b->LstBandes->First();
    }
    catch(...)
    {
        return NULL;
    }
    return b;
}
//---------------------------------------------------------------------------

TCoordonnee  __fastcall TListOfBandes::GetTop( )const
{
    if( BandeOwner)      return BandeOwner->Top;
    else if( EtatOwner)  return EtatOwner->Top;
    else                 return TCoordonnee();  // zero
}
//---------------------------------------------------------------------------

TCoordonnee  __fastcall TListOfBandes::GetHauteur( )const
{
    TCoordonnee cHauteur;
    for( int i = 0; i < Count; i++)
    {
        cHauteur.PixelsY = cHauteur.PixelsY + Bandes[ i]->Hauteur.PixelsY;
//        if( Bandes[ i]->Type == e_EnTete) bEntete = true;
//        if( Bandes[ i]->Type == e_Pied)   bPied = true;
    }
/*    if( !m_BandeOwner && m_EtatOwner && m_DocOwner->LstBandes)
    {   // On est sur la liste de l'Etat
        TBande *b = m_DocOwner->LstBandes->SearchBande( e_EnTete);
        if( !bEntete && b) cHauteur = cHauteur + b->Hauteur;
        b = m_DocOwner->LstBandes->SearchBande( e_Pied);
        if( !bPied && b) cHauteur = cHauteur + b->Hauteur;
    }*/

    return cHauteur;
}
//---------------------------------------------------------------------------

TBande*  __fastcall TListOfBandes::GetBande( const TCoordonnee &cY)const
{
    for( int i = 0; i < Count; i++)
    {
        TBande *b = Bandes[ i];
        if( b->IsInBande( cY))
        {
            if( b->LstBandes)
                return b->LstBandes->GetBande( cY);
            else
                return b;
        }
    }
    return NULL;
}
//---------------------------------------------------------------------------

void  __fastcall TListOfBandes::GetComposantsIn( TList* ListeCp, const TCoorRect &rSelection, const TBande* BandeQuiDemande, bool bSelEntier)const
{
    TBande* b;
    for( int i = 0; i < Count; i++)
    {
        b = Bandes[ i];
        if( b->LstBandes)
            b->LstBandes->GetComposantsIn( ListeCp, rSelection, BandeQuiDemande, bSelEntier);
        else
        {
            RECT rcBande, rcTmp, rcSel = rSelection.RECTPixels;
            rcBande.left = 0;              rcBande.right  = EtatOwner->Largeur.PixelsX;
            rcBande.top = b->Top.PixelsY;  rcBande.bottom = rcBande.top + b->Hauteur.PixelsY;

            if( ::IntersectRect( &rcTmp, &rcBande, &rcSel))
                b->LstComposants->GetComposantsIn( ListeCp, rSelection, BandeQuiDemande, bSelEntier);
        }
    }
}
//---------------------------------------------------------------------------

void __fastcall TListOfBandes::GetCpCalc( TList* ListeCpCalcCol, TList* ListeCpCalcLigne, TList* LstCpExtensibles, bool &bCpNbPages)const
{
    TBande* b;
    for( int i = 0; i < Count; i++)
    {
        b = Bandes[ i];
        if( b->LstBandes)
            b->LstBandes->GetCpCalc( ListeCpCalcCol, ListeCpCalcLigne, LstCpExtensibles, bCpNbPages);
        else
        {
            b->LstComposants->GetCpCalc( ListeCpCalcCol, ListeCpCalcLigne, LstCpExtensibles, bCpNbPages);
        }
    }
}
//---------------------------------------------------------------------------

TComposant* __fastcall TListOfBandes::GetComposant( const TCoordonnee &X, const TCoordonnee &Y, Type_CoinSelectionne &CoinCourant)const
{
    CoinCourant = sel_Aucun;
    TBande* b = GetBande( Y);
    if( b)  return b->LstComposants->GetComposant( X, Y, CoinCourant);
    return NULL;
}
//---------------------------------------------------------------------------
TComposant* __fastcall TListOfBandes::GetComposant( const AnsiString &s)const
{
    TComposant *Cp = NULL;
    for( int i = 0; !Cp && i < Count; i++)
    {
        Cp = Bandes[ i]->GetComposant( s);
    }
    return Cp;
}
//---------------------------------------------------------------------------

void __fastcall TListOfBandes::GetComposants( enum TypesComposants TypeCp, TStrings *LstCp)const
{
    for( int i = 0; i < Count; i++)
    {
        Bandes[ i]->GetComposants( TypeCp, LstCp);
    }
}
//---------------------------------------------------------------------------
void __fastcall TListOfBandes::InvalideComposantsAttacheA( const AnsiString &ChpAttache)
{
    for( int i = 0; i < Count; i++)
    {
        Bandes[ i]->InvalideComposantsAttacheA( ChpAttache);
    }
}
//---------------------------------------------------------------------------
void __fastcall TListOfBandes::NettoieComposantsAttacheA( const AnsiString &ChpAttache)
{
    for( int i = 0; i < Count; i++)
    {
        Bandes[ i]->NettoieComposantsAttacheA( ChpAttache);
    }
}
//---------------------------------------------------------------------------
void __fastcall TListOfBandes::Nettoie( )
{
    for( int i = 0; i < Count; i++)
    {
        Bandes[ i]->Nettoie();
    }
    m_TrueList->Clear();
}
//---------------------------------------------------------------------------

void __fastcall TListOfBandes::RefreshValRupture( )
{
    for( int i = 0; i < Count; i++)
    {
        Bandes[ i]->RefreshValRupture();
    }
}
//---------------------------------------------------------------------------

TBande* __fastcall TListOfBandes::LastBande()const
{
    if( Count)
        return Bandes[ Count-1];
    return NULL;
}
//---------------------------------------------------------------------------

TBande* __fastcall TListOfBandes::FirstBande()const
{
    if( Count)
        return Bandes[ 0];
    return NULL;
}
//---------------------------------------------------------------------------

TComposant* __fastcall TListOfBandes::GetCpPrecedentSuivant( bool bPrec, const TBande* Bande)const
{
    const TBande* b = NULL;
    TComposant* CpReturn = NULL;
    b = Bande;
    do{
        if( b) b = bPrec? PreviousBande( b) : NextBande( b);
        else   b = bPrec? LastBande( ) : FirstBande( );
        if( b)
            CpReturn = b->LstComposants->GetPrecedentSuivant( bPrec, NULL);
    }while( b && !CpReturn);

    if( !CpReturn)
        CpReturn = EtatOwner->LstBandes->GetCpPrecedentSuivant( bPrec, NULL);
    return CpReturn;
}




